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

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

  initialize() {
    this.control = this.getScript(Control);
    this.el = this.control.getEl();
    super.initialize();
  }

  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') {
      this.auditService.logActionAudit(this.eventType);
    }
  }
}