import {ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef} from "@angular/core";
import {
  AbstractButton,
  ComboBox,
  FileModel,
  FileUtils,
  MessagesService,
  NotNull,
  ObjectRef,
  DateTimePicker,
  TextArea
} from "@webbpm/base-package";
import {ExportDataRpcService} from "../generated/rpc/ExportDataRpcService";
import {ExportDataRequest} from "../generated/dto/ExportDataRequest";

/**
 * @author: kochetkov
 */
@Component({
             selector: 'export-data-button-component',
             templateUrl: './ConfigExecuteBtn.html',
             changeDetection: ChangeDetectionStrategy.OnPush,
             standalone: false
           })
export class ExportDataBtn extends AbstractButton {

  @ObjectRef()
  @NotNull()
  public dataTypeField: ComboBox;

  @ObjectRef()
  @NotNull()
  public ervuIdsField: TextArea;

  @ObjectRef()
  public startDate: DateTimePicker;

  @ObjectRef()
  public endDate: DateTimePicker;

  private rpc: ExportDataRpcService;
  private messagesService: MessagesService;

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

  initialize() {
    super.initialize();
    this.rpc = this.getScript(ExportDataRpcService);
    this.messagesService = this.getScript(MessagesService);
  }

  doClickActions(): Promise<any> {
    const type = this.dataTypeField.getValue();
    const value = this.ervuIdsField.getValue();

    const ids = value == null ? value : value.replace(/[{}]/g, '')
        .split(',')
        .map(id => id.trim().replace(/"/g, ''));

    let exportDataRequest = new ExportDataRequest();
    exportDataRequest.ids = ids;
    exportDataRequest.type = type;
    exportDataRequest.startDate = this.startDate ? this.startDate.getDateValue() : null;
    exportDataRequest.endDate = this.endDate ? this.endDate.getDateValue() : null;
    return this.rpc.exportData(exportDataRequest)
        .then((data: FileModel) => {
          FileUtils.downloadFile(data.fileName, data.fileContent);
        }).catch(reason => {
          return this.messagesService.error(reason);
        });
  }

  getFocusElement(): HTMLInputElement {
    return this.el.nativeElement.querySelector('button');
  }
}
