import {AnalyticalScope, Behavior, Container, ControlWithValue} from "@webbpm/base-package";
import {HttpClient} from "@angular/common/http";
import {PersonData} from "./PersonData";
import {CookieService} from "ngx-cookie";
import {PersonDataModel} from "../generated/ru/micord/ervu/security/esia/model/PersonDataModel";

@AnalyticalScope(Container)
export class PersonDataRoot extends Behavior{

  private container: Container;

  initialize() {
    super.initialize();
    this.container = this.getScript(Container);
    let personScripts: PersonData[] = this.container.getScriptsInThisAndChildren(PersonData);
    let httpClient = this.injector.get(HttpClient);
    let cookieService = this.injector.get(CookieService);
    if (cookieService.get("webbpm.ervu-lkrp-fl")) {
      httpClient.get<PersonDataModel>("esia/person")
          .toPromise()
          .then(personModel => {
            if (personModel == null) {
              return;
            }
            for (let person of personScripts) {
                let control: ControlWithValue = person.getScriptInObject(person.getObjectId(),
                                                                         'component.ControlWithValue');
                control.setValue(personModel[person.personDataId]);
            }
          });
    }
  }
}
