import {Container, FieldData, Visible, Event} from "@webbpm/base-package";
import {ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef} from "@angular/core";
import {ErvuDataService} from "../../../modules/app/service/ervu-data.service";
import {LoadFormField} from "../field/LoadFormField";
import {Subscription} from "rxjs";

@Component({
  moduleId: module.id,
  selector: 'load-form',
  templateUrl: './../../../../../src/resources/template/component/container/Form.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class LoadForm extends Container {

  @Visible("false")
  public formLoaded: Event<void> = new Event<void>(() => true);

  private ervuDataService: ErvuDataService;
  private subscription: Subscription;
  private fields: any[];
  private fieldDataList: FieldData[];

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

  public fireOnLoadEvent(): void {
    super.fireOnLoadEvent();
    this.formLoaded.trigger();
  }

  protected loadContainer(): Promise<any> {
    return this.fieldDataList ? this.loadData() : Promise.resolve();
  }

  initialize() {
    super.initialize();
    this.fields = this.getScriptsInChildren(LoadFormField);
    this.ervuDataService = this.injector.get(ErvuDataService);
    this.subscription = this.ervuDataService.message.subscribe(value => {
      if (value) {
        this.fieldDataList = [];
        this.fields.forEach(field => {
          let fieldData: FieldData = new FieldData();
          fieldData.componentGuid = field.objectId;
          fieldData.value = value[field.id];
          this.fieldDataList.push(fieldData);
        });
        this.loadData();
      }
    });
  }

  loadData(): Promise<any> {
    return this.setData(this.fieldDataList);
  }

  ngOnDestroy() {
    super.ngOnDestroy();
    this.subscription.unsubscribe();
  }
}
