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

/**
 * @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;
  @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 =  this.ervuIdField.getValue();
    if (value && this.methodPath.trim().length !== 0) {
      const ids = value.replace(/[{}]/g, '')
          .split(',')
          .map(id => id.trim().replace(/"/g, ''));

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

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