import {ChangeDetectionStrategy, ChangeDetectorRef, Component, Input} from "@angular/core";
import {Process, TaskService, ProcessDefinitionResource, ProcessService} from "@webbpm/base-package";

@Component({
  moduleId: module.id,
  selector: 'process',
  templateUrl: '../../../../../src/resources/template/app/component/process_list.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProcessListComponent {

  @Input()
  public processList: Process[];
  @Input()
  public errorMessage: string;

  constructor(private processDefinitionResource: ProcessDefinitionResource,
              private taskService: TaskService,
              private cd: ChangeDetectorRef,
              private processService: ProcessService) {
    this.processList = [];
    this.loadProcessList();
  }

  loadProcessList() {
    this.processDefinitionResource.list().then(
        (processList) => {
          this.processList = processList;
          this.cd.markForCheck();
        },
        () => {
          this.errorMessage = "Error load process list";
          this.cd.markForCheck();
        })
  }

  startProcess(processDefinitionId: string) {
    this.processService.start(processDefinitionId, null).then(
        (processInstanceId: number) => {
          this.taskService.startAndOpenNextTask(processInstanceId);
        }
    );
  }
}