import { TypeEditor } from "../TypeEditor.js";
import EmptyView from "../../../../src/view/elements/EmptyView.js";
import { rgb2hex } from "../../../../src/core/color/hex/rgb2hex.js";

export class ColorEditor extends TypeEditor {
    build(parent, field) {

        /**
         * @type {Color}
         */
        const color = field.adapter.read(parent, field.name);

        const view = new EmptyView({
            tag: 'input'
        });

        view.attr({
            type: "color"
        });

        function sync_up() {
            view.attr({
                value: `#${rgb2hex(color.r * 255, color.g * 255, color.b * 255)}`
            })
        }

        function sync_down(e) {
            const color_value = e.target.value;

            color.parse(color_value);
        }

        view.on.linked.add(sync_up);
        view.el.addEventListener('input', sync_down, false);
        view.el.addEventListener('change', sync_down, false);

        return view;
    }
}
