import { Component, Input, AfterViewInit, Output, EventEmitter } from "@angular/core";
import { NgParameter } from "../../formulaire/ngparam";
import { DialogEditParamValuesComponent } from "../dialog-edit-param-values/dialog-edit-param-values.component";
import { MatDialog } from "@angular/material";
import { ParamValueMode, Observer } from "jalhyd";

@Component({
    selector: "param-values",
    templateUrl: "./param-values.component.html",
    styleUrls: [
        "./param-values.component.scss"
    ]
})
export class ParamValuesComponent implements AfterViewInit, Observer {

    @Input()
    public param: NgParameter;

    @Input()
    public title: string;

    /**
     * événement signalant un changement de valeur du modèle
     */
    @Output()
    protected change = new EventEmitter<any>();

    constructor(
        private editValuesDialog: MatDialog
    ) { }

    public get isMinMax() {
        return this.param.valueMode === ParamValueMode.MINMAX;
    }

    public get isListe() {
        return this.param.valueMode === ParamValueMode.LISTE;
    }

    public get infoText() {
        return NgParameter.preview(this.param.paramDefinition);
    }

    public openDialog() {
        // modification des valeurs variables
        this.editValuesDialog.open(
            DialogEditParamValuesComponent,
            {
                disableClose: true,
                data: {
                    param: this.param
                }
            }
        );
    }

    public ngAfterViewInit() {
        // open dialog when switching to this mode, but only the first time this component is built,
        // otherwise switching back from another calc tab will trigger the dialog again
        if (this.param.valueMode === ParamValueMode.MINMAX && this.param.minValue === undefined) {
            // use Promise trick to introduce a pseudo-timeout and avoid ExpressionChangedAfterItHasBeenCheckedError
            Promise.resolve().then(() => {
                this.openDialog();
            });
        }
        // subscribe to parameter values change (through dialog actions)
        this.param.addObserver(this);
    }

    /**
     * événement de changement de la valeur du modèle
     */
    private emitModelChanged() {
        this.change.emit({ "action": "model", "value": this.param.getValue() });
    }

    public update(sender: any, data: any): void {
        if (sender instanceof DialogEditParamValuesComponent) {
            switch (data.action) {
                case "ngparamAfterValue":
                    // tell the form to clear the results
                    this.emitModelChanged();
                    break;
            }
        }
    }

}