import {AnalyticalScope, Behavior, Control, NotNull} from "@webbpm/base-package";
import {AuditService} from "./service/AuditService";
import {ElementRef, Input} from "@angular/core";
import {LinkEventTypeEnum} from "./component/enum/LinkEventTypeEnum";

@AnalyticalScope(Control)
export class LinkClickHandler extends Behavior {
  @Input()
  @NotNull()
  public eventType: LinkEventTypeEnum;
  private control: Control;
  private auditService: AuditService;
  private el: ElementRef

  public initialize() {
    super.initialize();
    this.control = this.getScript(Control);
    this.injector.get(AuditService);
    this.auditService = this.injector.get(AuditService);
    this.el = this.control.getEl();
  }

  bindEvents() {
    super.bindEvents();
    if (this.el) {
      this.el.nativeElement.addEventListener('click',
                                             (event: MouseEvent) => this.onClickFunction(event));
    }
  }

  unbindEvents() {
    super.unbindEvents();
    if (this.el) {
      this.el.nativeElement.removeEventListener('click',
                                                (event: MouseEvent) => this.onClickFunction(event));
    }
  }

  private onClickFunction(event: MouseEvent) {
    const target = event.target as HTMLElement;
    if (target.tagName === 'A') {
      if (this.eventType === LinkEventTypeEnum.DOWNLOAD_EXAMPLE
          || this.eventType === LinkEventTypeEnum.DOWNLOAD_TEMPLATE) {
        const href = target.getAttribute('href');
        if (href) {
          const fileName = this.extractFileNameFromHref(href);
          this.auditService.logActionAudit(this.eventType, null, fileName);
        }
      }
      else {
        this.auditService.logActionAudit(this.eventType);
      }
    }
  }

  private extractFileNameFromHref(href: string): string {
    const parts = href.split('/');
    const fileNameWithExtension = parts[parts.length - 1];
    return fileNameWithExtension.split('?')[0];
  }
}
