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

/**
 * @author: a.petrov
 */
@Component({
  moduleId: module.id,
  selector: 'config-execute-button-component',
  templateUrl: './../../../src/resources/template/app/component/ConfigExecuteBtn.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ConfigExecuteBtn extends AbstractButton {

  @ObjectRef()
  @NotNull()
  public ervuIdField: TextArea;
  @ObjectRef()
  public startDate: DateTimePicker;
  @ObjectRef()
  public endDate: DateTimePicker;
  @NotNull()
  public methodPath: string;
  private script: ConfigExecutorRpcService;
  private messagesService: MessagesService;

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

  initialize() {
    super.initialize();
    this.script = this.getScript(ConfigExecutorRpcService);
    this.messagesService = this.injector.get(MessagesService);
  }

  doClickActions(): Promise<any> {
    const value: string =  this.ervuIdField.getValue();
    if (value && this.methodPath.trim().length !== 0) {
      const ids: string[] = value.replace(/[{}]/g, '')
          .split(',')
          .map(id => id.trim().replace(/"/g, ''));

      let configExecuteRequest: ConfigExecuteRequest = new ConfigExecuteRequest();
      let withDate = false;
      configExecuteRequest.ids = ids;
      if (this.startDate || this.endDate) {
        withDate = true;
        configExecuteRequest.startDate = this.startDate ? this.startDate.getDateValue() : null;
        configExecuteRequest.endDate = this.endDate ? this.endDate.getDateValue() : null;
      }

      return this.script.callConfigExecutor(this.methodPath, configExecuteRequest, withDate, true)
          .then(successMsg => this.messagesService.success(successMsg))
          .catch(error => Promise.reject(error));
    }
  }

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