import {Form} from "@webbpm/base-package";
import {ChangeDetectionStrategy, Component} from "@angular/core";
import {ErvuDataService} from "../../../modules/app/service/ervu-data.service";
import {Subscription} from "rxjs";
import {LoadFormRpcService} from "../../../generated/ru/micord/ervu/service/rpc/LoadFormRpcService";

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

  private formRpcService: LoadFormRpcService;
  private ervuDataService: ErvuDataService;
  private subscription: Subscription;

  private valuesData: string;

  initialize() {
    super.initialize();
    this.formRpcService = this.getScript(LoadFormRpcService);
    this.ervuDataService = this.injector.get(ErvuDataService);
    this.subscription = this.ervuDataService.message.subscribe(value => {
      if (value) {
        this.valuesData = value;
        this.loadData();
      }
    });
  }

  loadData(): Promise<any> {
    return this.formRpcService
        .loadData(this.valuesData)
        .then(fieldDataList => this.setData(fieldDataList))
        .catch(reason => {
          throw new Error(reason);
        });
  }

  saveData(): Promise<any> {
    return;
  }

  deleteData(): Promise<void> {
    return;
  }

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