import { useState } from "react";
import { AddEvent, AppEvent, DelEvent, Env, UpdateEvent } from "../../models/Env";
import { EnvParam } from "../../models/EnvParam";
import { EnvironmentParam } from "./EnvironmentParam";

export function Environment(props: { envs: Env[], onChanged: (env: Env) => void, onSelected: (envId: number) => void }) {
    const [currEnv, setCurrEnv] = useState(props.envs[0]);

    function handleParamChanged(e: AppEvent<EnvParam>) {
        let isChanged = false;
        let env = currEnv;

        if (e instanceof DelEvent) {
            env = currEnv.delParam(e.payload);
            isChanged = true;
        }

        if (e instanceof AddEvent) {
            env = currEnv.addParams(e.payload);
            isChanged = true;
        }

        if (e instanceof UpdateEvent) {
            env = currEnv.updateParams(e.payload);
            isChanged = true;
        }

        if (isChanged) {
            let idx = props.envs.findIndex(x => x.id === env.id);
            if (idx > -1) {
                props.envs[idx] = env;
                props.onChanged(props.envs[idx]);
                setCurrEnv(env);
            }
        }
    }

    const selectOptions = props.envs.map((x) => <option key={x.id} value={x.id} >{x.name}</option>);
    const paramCtrls = currEnv.params.map(x =>
        <EnvironmentParam key={`${currEnv.id}-${x.id}`}
            param={new EnvParam(x.id, x.name, x.value)}
            onChanged={handleParamChanged}
            isNew={false} />);

    return (
        <>
            <div className="row">
                <select
                    id="environments"
                    name="environments"
                    aria-label="Environments"
                    className="form-select"
                    onChange={x => {
                        let id = Number.parseInt(x.target.value);
                        setCurrEnv(props.envs[id]);
                        props.onSelected(id);
                    }}>
                    {selectOptions}
                </select>
            </div>
            <div className="row">Params</div>
            {paramCtrls}
            <EnvironmentParam key={`${currEnv.id}-new`}
                param={new EnvParam(-1, "", "")}
                onChanged={handleParamChanged}
                isNew={true}
            />
        </>
    );
}


