import { TypeEditor } from "../../TypeEditor.js";
import DropDownSelectionView from "../../../../../src/view/elements/DropDownSelectionView.js";
import List from "../../../../../src/core/collection/list/List.js";
import { objectKeyByValue } from "../../../../../src/core/model/object/objectKeyByValue.js";

export class EnumEditor extends TypeEditor {
    constructor(type) {
        super();

        this.type = type;
    }

    build(parent, field, registry) {

        const valueSet = this.type;

        function read() {
            return field.adapter.read(parent, field.name);
        }

        function write(v) {
            field.adapter.write(parent, field.name, v);
        }

        const ctrl = new DropDownSelectionView(
            new List(Object.keys(valueSet)), {
                changeListener(key) {
                    const v = valueSet[key];

                    write(v);
                }
            }
        );

        ctrl.on.linked.add(() => {
            ctrl.setSelectedValue(objectKeyByValue(valueSet, read()));
        })

        return ctrl;
    }
}
