import {
  AbstractButton,
  AnalyticalScope,
  Behavior,
  Event,
  Visible
} from "@webbpm/base-package";
import {ExtractRpcService} from "../../../generated/ru/micord/ervu/service/rpc/ExtractRpcService";

@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>();

  private button: AbstractButton;
  private rpc: ExtractRpcService;
  private onClickFunction: Function;

  initialize() {
    super.initialize();
    this.button = this.getScript(AbstractButton);
    this.rpc = this.getScript(ExtractRpcService);
    this.onClickFunction = () => {
      this.rpc.getExtract()
          .then(fileData => {
            const newBlob = new Blob([fileData['file']],
                                     { type: fileData['fileType'] });

            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
              window.navigator.msSaveBlob(newBlob);
            }
            else {
              const data = window.URL.createObjectURL(newBlob);
              const link = document.createElement("a");
              link.href = data;
              link.download = fileData['fileName'];
              link.click();
              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);
  }
}
