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({
  selector: 'config-execute-button-component',
  templateUrl: './ConfigExecuteBtn.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: false
})
export class ConfigExecuteBtn extends AbstractButton {

  @ObjectRef()
  @NotNull()
  public ervuIdField: TextArea;
  @ObjectRef()
  public startDate: DateTimePicker;
  @ObjectRef()
  public endDate: DateTimePicker;
  @NotNull()
  public methodPath: string;

  private rpcService: ConfigExecutorRpcService;
  private messagesService: MessagesService;

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

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

  doClickActions(): Promise<any> {

    if (this.methodPath.trim().length == 0) {
      return;
    }

    const ids: string[] = this.ervuIdField.getValue()
                          ? ConfigExecuteBtn.parseIds(this.ervuIdField.getValue())
                          : new Array<string>();

    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.rpcService.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');
  }

  private static parseIds(value: string): string[] {
    return value.replace(/[{}]/g, '')
        .split(',')
        .map(id => id.trim().replace(/"/g, ''));
  }

}
