import { MatDialogRef, MAT_DIALOG_DATA } from "@angular/material";
import { Inject, Component } from "@angular/core";
import { I18nService } from "../../services/internationalisation/internationalisation.service";

@Component({
    selector: "dialog-save-session",
    templateUrl: "dialog-save-session.component.html",
    styleUrls: ["dialog-save-session.component.scss"]
})
export class DialogSaveSessionComponent {

    public calculators: any[];

    public fileName = "session";

    public dependenciesProblems: any[] = [];

    constructor(
      public dialogRef: MatDialogRef<DialogSaveSessionComponent>,
      private intlService: I18nService,
      @Inject(MAT_DIALOG_DATA) public data: any
    ) {
      this.calculators = data.calculators;
      // run dependency checking at first
      this.checkLinkedParamsAndModelsDependencies();
    }

    public selectAll() {
      for (const c of this.calculators) {
          c.selected = true;
      }
      // re-run dependency checking
      this.checkLinkedParamsAndModelsDependencies();
    }

    public selectNone() {
      for (const c of this.calculators) {
        c.selected = false;
      }
      // re-run dependency checking
      this.checkLinkedParamsAndModelsDependencies();
    }

    /**
     * Checks the dependencies between Nubs :
     *  - linked params depend on their targets
     *  - PabCloisons depend on their models
     */
    public checkLinkedParamsAndModelsDependencies() {
      console.log("CLPMD !", this.calculators);
      this.dependenciesProblems = [];
      // for all checked Nubs
      this.calculators.forEach((c) => {
        if (c.selected) {
          // do all required nubs are checked ?
          c.requires.forEach((r) => {
            if (! this.isCalculatorOrParentSelected(r)) {
              const realUid = this.getUidOrParentUid(r);
              const depTitle = this.getTitleFromUid(realUid);
              this.dependenciesProblems.push({
                requiring: c.title,
                required: depTitle,
                requiredUid: realUid,
                message: c.title + " " + this.intlService.localizeText("INFO_REQUIRES") + " " + depTitle
              });
            }
          });
        }
      });
    }

    public fixDependencies() {
      for (const dp of this.dependenciesProblems) {
        this.selectRequiredModule(dp.requiredUid);
      }
    }

    private isCalculatorOrParentSelected(uid: string): boolean {
      let isSelected = false;
      this.calculators.forEach((c) => {
        if (c.uid === uid || c.children.includes(uid)) {
          isSelected = c.selected;
        }
      });
      return isSelected;
    }

    private getUidOrParentUid(uid: string): string {
      let realUid: string;
      this.calculators.forEach((c) => {
        if (c.uid === uid || c.children.includes(uid)) {
          realUid = c.uid;
        }
      });
      return realUid;
    }

    private getTitleFromUid(uid: string): string {
      let title: string;
      this.calculators.forEach((c) => {
        if (c.uid === uid) {
          title = c.title;
        }
      });
      return title;
    }

    private selectRequiredModule(uid: string) {
      this.calculators.forEach((c) => {
        if (c.uid === uid) {
          c.selected = true;
        }
      });
      // re-run dependency checking
      this.checkLinkedParamsAndModelsDependencies();
    }

    public saveSession() {
      this.dialogRef.close({
        calculators: this.calculators,
        filename: this.fileName
      });
    }

    public get atLeastOneCheckboxSelected() {
      let ok = false;
      for (const c of this.calculators) {
        ok = (ok || c.selected);
      }
      return ok;
    }

    public get uitextSave() {
      return this.intlService.localizeText("INFO_OPTION_SAVE");
    }

    public get uitextCancel() {
      return this.intlService.localizeText("INFO_OPTION_CANCEL");
    }

    public get uitextAll() {
      return this.intlService.localizeText("INFO_OPTION_ALL");
    }

    public get uitextNone() {
      return this.intlService.localizeText("INFO_OPTION_NONE");
    }

    public get uitextSaveSessionTitle() {
      return this.intlService.localizeText("INFO_DIALOG_SAVE_SESSION_TITLE");
    }

    public get uitextFilenameInput() {
      return this.intlService.localizeText("INFO_DIALOG_SAVE_SESSION_FILENAME");
    }

    public get uitextFixMissingDependencies() {
      return this.intlService.localizeText("INFO_DIALOG_FIX_MISSING_DEPENDENCIES");
    }

    public onEnterPressed(event) {
        this.saveSession();
        return false; // stops event propagation
    }
}