import { TypeEditor } from "../TypeEditor.js";
import EmptyView from "../../../../src/view/elements/EmptyView.js";
import ImageView from "../../../../src/view/elements/image/ImageView.js";
import ButtonView from "../../../../src/view/elements/button/ButtonView.js";
import { url_to_data_url } from "../../../../src/core/binary/url_to_data_url.js";
import { is_data_url } from "../../../../src/core/binary/is_data_url.js";
import { LargeStringEditor } from "./LargeStringEditor.js";

export class ImagePathEditor extends TypeEditor {
    inline = true;

    build(parent, field, registry) {
        const url_editor = new LargeStringEditor();

        const editor = url_editor.build(parent, field, registry);

        const r = new EmptyView({
            css: {
                display: "flex",
                flexDirection: "row"
            }
        });

        const vPreview = new ImageView(field.adapter.read(parent, field.name));

        vPreview.size.set(32, 32);

        const b_toDataURL = new ButtonView({
            classList: ['convert-to-data-url', 'embed'],
            async action() {
                const url = await url_to_data_url(field.adapter.read(parent, field.name));

                field.adapter.write(parent, field.name, url);

                // update editor value
                editor.methods.set_value(url);

                input_changed();
            }
        });

        b_toDataURL.attr({
            title: 'Convert URL into DATA_URL, embedding the data. This allows to bypass CORRS restrictions if the URL points to a different origin from the one where the texture resides'
        });

        function update_data_url_status() {
            const url = field.adapter.read(parent, field.name);

            const can_convert = typeof url === "string"
                && field.adapter.writable
                && !is_data_url(url)
            ;

            if (can_convert) {
                // offer encoding option
                r.addChild(b_toDataURL);
            } else {
                // nothing
                if (r.hasChild(b_toDataURL)) {
                    r.removeChild(b_toDataURL);
                }
            }
        }

        function input_changed() {
            const url = field.adapter.read(parent, field.name);

            vPreview.__setSource(url);

            update_data_url_status();
        }

        r.addChild(vPreview);
        r.addChild(editor.view);

        editor.signals.input_changed.add(input_changed);

        r.on.linked.add(update_data_url_status);

        return r;
    }
}
