import {ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef} from "@angular/core";
import {AbstractButton, MessagesService, NotNull, ObjectRef} from "@webbpm/base-package";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {InMemoryStaticGrid} from "../grid/InMemoryStaticGrid";
import {Subscription} from "rxjs";

/**
 * @author: Eduard Tihomirov
 */
@Component({
             moduleId: module.id,
             selector: 'ervu-download-file-button',
             templateUrl: "./../../../../../src/resources/template/ervu/component/button/Button.html",
             changeDetection: ChangeDetectionStrategy.OnPush
           })
export class ErvuDownloadFileButton extends AbstractButton {
  private httpClient: HttpClient;
  private messageService: MessagesService;
  private gridLoadedSubscription: Subscription;

  @ObjectRef()
  @NotNull()
  public grid: InMemoryStaticGrid;

  @NotNull()
  public fileName: string;

  @NotNull()
  public noFileMessage: string;

  constructor(el: ElementRef, cd: ChangeDetectorRef) {
    super(el, cd);
  }

  initialize() {
    super.initialize();
    this.httpClient = this.injector.get(HttpClient);
    this.messageService = this.injector.get(MessagesService);
    if (this.grid.isInitialized() && this.grid.getRowDataSize() > 0) {
      this.setEnabled(true);
      this.setVisible(true);
    }
    this.gridLoadedSubscription = this.grid.gridLoaded.subscribe(() => {
      if (this.grid.getRowDataSize() > 0) {
        this.setEnabled(true);
        this.setVisible(true);
      }
      else {
        this.setEnabled(false);
        this.setVisible(false);
      }
    });
  }

  ngOnDestroy() {
    super.ngOnDestroy();
    this.gridLoadedSubscription.unsubscribe();
  }

  public doClickActions(): Promise<any> {
    return this.httpClient.get('kafka/excerpt', {
      responseType: 'blob',
      headers: new HttpHeaders({'Client-Time-Zone' : Intl.DateTimeFormat().resolvedOptions().timeZone}),
      observe: 'response'
    }).toPromise().then((response) => {
      if (response.status == 204) {
        this.messageService.info(this.noFileMessage)
      }
      const contentDisposition = response.headers.get('Content-Disposition');
      const url = window.URL.createObjectURL(response.body);
      const a = document.createElement('a');
      const fileNameMatch = contentDisposition.match(/filename\*=?UTF-8''(.+)/i);
      if (fileNameMatch && fileNameMatch.length > 1) {
        this.fileName = decodeURIComponent(fileNameMatch[1].replace(/\+/g, '%20'));
      }
      a.href = url;
      a.download = this.fileName;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      a.remove();
    });
  }
}
