import {AnalyticalScope, Behavior, Container, ControlWithValue} from "@webbpm/base-package";
import {HttpClient} from "@angular/common/http";
import {OrgData} from "./OrgData";
import {OrgInfoModel} from "../generated/ru/micord/ervu/security/esia/model/OrgInfoModel";
import {AuthenticationService} from "../modules/security/authentication.service";

@AnalyticalScope(Container)
export class OrgDataRoot extends Behavior {

  private container: Container;

  initialize() {
    super.initialize();
    this.container = this.getScript(Container);
    let orgScripts: OrgData[] = this.container.getScriptsInThisAndChildren(OrgData);
    let httpClient = this.injector.get(HttpClient);
    let cookieService = this.injector.get(AuthenticationService);

    if (cookieService.isAuthenticated()) {
      httpClient.get<OrgInfoModel>("esia/org")
          .toPromise()
          .then(orgInfoModel => {
            if (orgInfoModel == null) {
              return;
            }
            for (let orgData of orgScripts) {
              let control: ControlWithValue = orgData.getScriptInObject(orgData.getObjectId(),
                                                                        'component.ControlWithValue');
              control.setValue(orgInfoModel[orgData.dataId]);
            }
          });
    }
  }
}
