/* Essentials YOOtheme Pro 2.2.16 build 0813.1608; ZOOlanders https://www.zoolanders.com; Copyright (C) Joolanders, SL; http://www.gnu.org/licenses/gpl.html GNU/GPL */

import hooks from '@yootheme/hooks';
import essentials from 'essentials';
import { LayoutsManager, NodeModal } from './components';

['layoutsModalTabs', 'elementsModalTabs'].forEach((eventName) => {
    hooks.before('app.init', ({ extend }) => {
        extend({
            events: {
                [eventName]({ result = [] }) {
                    const libraries = essentials.LayoutLibrary.libraries.filter((lib) =>
                        essentials.LayoutLibrary.storageOf(lib)
                    );

                    libraries.forEach((library) => {
                        result.push({
                            name: library.name,
                            component: {
                                render(h) {
                                    return h(LayoutsManager, {
                                        props: {
                                            mode:
                                                eventName === 'layoutsModalTabs'
                                                    ? 'layouts'
                                                    : 'presets',
                                            library: library.id,
                                        },
                                        on: {
                                            select: (node) => {
                                                this.$emit('select', node); // layoutsModalTabs
                                                this.$emit('resolve', node); // elementsModalTabs
                                            },
                                        },
                                    });
                                },
                            },
                        });
                    });

                    return result;
                },
            },
        });
    });
});

hooks.before('app.init', ({ extend }) => {
    extend({
        events: {
            saveNode: (e, node, builder) => {
                if (node.type === 'layout' || !essentials.LayoutLibrary.libraries.length) {
                    return;
                }

                builder
                    .$modal(NodeModal, {
                        builder,
                        node: { ...builder.clone(node), modified: new Date().toISOString() },
                        libraries: essentials.LayoutLibrary.libraries,
                    })
                    .show({ width: 'xlarge' })
                    .then(({ node, library } = {}) => {
                        if (!node || !library) {
                            return;
                        }

                        essentials.LayoutLibrary.saveNode(library, node);
                    });

                return false;
            },
        },
    });
});
