import {
  AnalyticalScope,
  Behavior,
  NotNull,
  Text
} from "@webbpm/base-package";
import { Router } from "@angular/router";
import { ElementRef, Injector } from '@angular/core';
import {FilterTransferService} from "./FilterTransferService";
import {FilterParams} from "./model/FilterParams";

@AnalyticalScope(Text)
export class TextClickHandlerScript extends Behavior {
  private text: Text;
  @NotNull()
  public filters: FilterParams[];
  @NotNull()
  public route: string;
  private el: ElementRef;
  private router: Router;
  private filterTransferService: FilterTransferService;

  constructor(pageId?: string, objectId?: string, injector?: Injector, interfaces?: any[]) {
    super(pageId, objectId, injector, interfaces);
  }

  public initialize() {
    super.initialize();
    this.text = this.getScript(Text);
    this.el = this.text.getEl();
    this.router = this.injector.get(Router);
    this.filterTransferService = this.injector.get(FilterTransferService);
  }

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

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

  private onClickFunction() {
    const filterData: Record<string, any> = {};
    this.filters.forEach(filter => {
      if (filter.key && filter.value) {
        filterData[filter.key] = filter.value;
      }
    });
    this.filterTransferService.setFilters(filterData);
    this.router.navigate([this.route]);
  }
}
