import {
  AbstractButton,
  AnalyticalScope,
  Behavior,
  Event,
  NotNull,
  Visible
} from "@webbpm/base-package";
import {HttpClient} from "@angular/common/http";

@AnalyticalScope(AbstractButton)
export class ExtractLoadService extends Behavior {

  @Visible("false")
  public successEvent: Event<boolean> = new Event<boolean>();
  @Visible("false")
  public errorEvent: Event<boolean> = new Event<boolean>();
  @NotNull()
  public formatRegistry: string;

  private button: AbstractButton;
  private httpClient: HttpClient;
  private onClickFunction: Function;

  initialize() {
    super.initialize();
    this.button = this.getScript(AbstractButton);
    this.httpClient = this.injector.get(HttpClient);
    this.errorEvent.subscribe(() => console.log("error event occurred", this.errorEvent));
    this.onClickFunction = () => {
      console.log("click event occurred");
      const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
      this.httpClient.get('extract/' + this.formatRegistry, {
        responseType: 'blob',
        headers: {
          "Client-Time-Zone": timeZone,
        },
        observe: 'response'
      }).toPromise()
          .then((response) => {
            const data = window.URL.createObjectURL(response.body);
            const link = document.createElement("a");
            link.href = data;
            const contentDisposition = response.headers.get('Content-Disposition');
            const fileNameMatch = contentDisposition.match(/filename\*=?UTF-8''(.+)/i);
            link.download = decodeURIComponent(fileNameMatch[1].replace(/\+/g, '%20'));
            document.body.appendChild(link);
            link.click();
            window.URL.revokeObjectURL(data);
            link.remove();
            this.successEvent.trigger();
          })
          .catch(() => {
            this.errorEvent.trigger();
          });
    }
  }

  bindEvents() {
    super.bindEvents();
    this.button.addClickListener(this.onClickFunction);
  }

  unbindEvents() {
    super.unbindEvents();
    this.button.removeClickListener(this.onClickFunction);
  }
}
