import uuid from 'uuid/v4';

export default class WsModalController {
  static $inject = ['$q', 'wsModalTriggerService'];
  constructor($q, modalTriggerService) {
    this.$q = $q;
    this.modalTriggerService = modalTriggerService;
  }

  $onInit = () => {
    this.triggerClass = this.triggerClass ||
      `button ${this.secondary ? 'secondary-action' : 'primary-action'}`;
    this.triggerId = this.triggerId || uuid();
  }

  showModal = () => {
    this.modalTriggerService.open(this.triggerId);
  }

  shouldShowModal = () =>
    this.modalTriggerService.isOpen(this.triggerId);

  actionInProgress = () => this.modalTriggerService.isInProgress(this.triggerId);
  err = () => this.modalTriggerService.getError(this.triggerId);

  doAction = () => {
    this.modalTriggerService.setError(this.triggerId, null);
    this.modalTriggerService.setIsInProgress(this.triggerId, true);
    this.$q.when(this.onAction())
      .then(() => { this.modalTriggerService.close(this.triggerId); })
      .catch((err) => {
        this.modalTriggerService.setError(this.triggerId, err);
        this.modalTriggerService.setIsInProgress(this.triggerId, false);
      });
  }

  doDismiss = () => {
    this.modalTriggerService.close(this.triggerId);
    this.onCancel();
  }
}
