"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ThemeEditor = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const FormLayout_1 = tslib_1.__importStar(require("../../components/FormLayout"));
const AdaptableContext_1 = require("../AdaptableContext");
const AdaptableInput_1 = tslib_1.__importDefault(require("../Components/AdaptableInput"));
const throttle_1 = tslib_1.__importDefault(require("../../Utilities/utils/throttle"));
const SimpleButton_1 = tslib_1.__importDefault(require("../../components/SimpleButton"));
const Panel_1 = tslib_1.__importDefault(require("../../components/Panel"));
const ThemeField_1 = require("./ThemeField");
const VariantSelector_1 = require("./VariantSelector");
const AdaptableHelper_1 = require("../../Utilities/Helpers/AdaptableHelper");
const Flex_1 = require("../../components/Flex");
const fields = [
    {
        name: 'Primary Color',
        type: 'color',
        variable: '--ab-color-primary',
    },
    {
        name: 'Primary Dark Color',
        type: 'color',
        variable: '--ab-color-primarydark',
    },
    {
        name: 'Primary Light Color',
        type: 'color',
        variable: '--ab-color-primarylight',
    },
    {
        name: 'Text on Primary Color',
        type: 'color',
        variable: '--ab-color-text-on-primary',
    },
    {
        name: 'Text on Primary Dark Color',
        type: 'color',
        variable: '--ab-color-text-on-primarydark',
    },
    {
        name: 'Default background',
        type: 'color',
        variable: '--ab-color-defaultbackground',
    },
    {
        name: 'Text Color on Default Background',
        type: 'color',
        variable: '--ab-color-text-on-defaultbackground',
    },
];
const ThemeEditor = (props) => {
    const adaptable = (0, AdaptableContext_1.useAdaptable)();
    const allThemes = adaptable.api.themeApi.getUserThemes();
    const [currentThemeObject, setCurrentThemeObject] = React.useState(() => {
        return adaptable.api.themeApi.getCurrentThemeObject();
    });
    const currentThemeAccessLevel = (0, AdaptableHelper_1.getAccessLevelForObject)(currentThemeObject, props.accessLevel);
    const currentThemeIsReadOnly = currentThemeAccessLevel !== 'Full';
    // THEME variables
    const themeVariables = currentThemeObject?.CSSVariables;
    const valuesFromTheme = fields.reduce((acc, field) => {
        if (themeVariables?.[field.variable]) {
            acc[field.variable] = themeVariables?.[field.variable];
        }
        return acc;
    }, {});
    React.useEffect(() => {
        setCurrentThemeObject(adaptable.api.themeApi.getCurrentThemeObject());
    }, [props.theme]);
    // This is needed when clearing variables, so the new value is pickedup up from the document
    React.useEffect(() => {
        const updateTheme = () => {
            const theme = adaptable.api.themeApi.getCurrentThemeObject();
            setCurrentThemeObject({ ...theme });
        };
        const themeChangedUnsubscribe = adaptable.api.eventApi.on('ThemeChanged', updateTheme);
        return () => {
            themeChangedUnsubscribe();
        };
    }, []);
    const handleNameDescriptionChangeThrottled = React.useMemo(() => {
        return (0, throttle_1.default)((key, value) => {
            const theme = adaptable.api.themeApi.getCurrentThemeObject();
            const newTheme = {
                ...theme,
                [key]: value,
            };
            adaptable.api.themeApi.editTheme(newTheme);
        }, 600);
    }, []);
    const handleDescriptionChange = React.useCallback((key, value) => {
        setCurrentThemeObject((prev) => ({ ...prev, [key]: value }));
        handleNameDescriptionChangeThrottled(key, value);
    }, []);
    const handleDeleteTheme = React.useCallback(() => {
        adaptable.api.themeApi.loadLightTheme();
        adaptable.api.themeApi.deleteUserTheme(currentThemeObject);
    }, []);
    const handleSaveName = () => {
        const name = currentThemeObject.Name;
        setCurrentThemeObject((prev) => ({ ...prev, Name: name }));
        handleNameDescriptionChangeThrottled('Name', name);
    };
    const handleVariantChange = (variant) => {
        const newTheme = { ...currentThemeObject };
        if (!variant) {
            delete newTheme.Variant;
        }
        else {
            newTheme.Variant = variant;
        }
        setCurrentThemeObject(newTheme);
        adaptable.api.themeApi.editTheme(newTheme);
    };
    const nameHasChanged = currentThemeObject.Name !== props.theme;
    const nameIsNotUnique = allThemes.some((theme) => theme.Uuid !== currentThemeObject.Uuid && currentThemeObject.Name === theme.Name);
    const saveNameDisabled = !nameHasChanged || nameIsNotUnique || currentThemeObject.Name === '';
    return (React.createElement(Panel_1.default, { header: React.createElement(Flex_1.Flex, { alignItems: "center", className: "twa:w-full" },
            React.createElement(Flex_1.Box, { className: "twa:flex-1" }, " Edit Custom Theme"),
            React.createElement(SimpleButton_1.default, { "data-name": "delete", accessLevel: currentThemeAccessLevel, icon: "delete", onClick: handleDeleteTheme, variant: "text" })) },
        React.createElement(FormLayout_1.default, null,
            React.createElement(FormLayout_1.FormRow, { label: "Theme Name" },
                React.createElement(AdaptableInput_1.default, { disabled: currentThemeIsReadOnly, className: "twa:mr-2", onChange: (event) => setCurrentThemeObject({
                        ...currentThemeObject,
                        Name: event.target.value.replace(/ /g, '-'),
                    }), value: currentThemeObject.Name ?? '' }),
                React.createElement(SimpleButton_1.default, { onClick: handleSaveName, disabled: saveNameDisabled || currentThemeIsReadOnly, icon: "save", hidden: currentThemeIsReadOnly }),
                React.createElement(Flex_1.Box, { className: "twa:text-2 twa:mt-1" }, "The name cannot contain spaces."),
                nameIsNotUnique && React.createElement(Flex_1.Box, { className: "twa:text-2 twa:text-error" }, "Name must be unique.")),
            React.createElement(FormLayout_1.FormRow, { label: "Description" },
                React.createElement(AdaptableInput_1.default, { disabled: currentThemeIsReadOnly, onChange: (event) => handleDescriptionChange('Description', event.target.value), value: currentThemeObject?.Description ?? '' })),
            React.createElement(FormLayout_1.FormRow, { label: "Variant" },
                React.createElement(VariantSelector_1.VariantSelector, { onChange: handleVariantChange, theme: currentThemeObject, disabled: currentThemeIsReadOnly })),
            fields.map((field) => {
                return (React.createElement(ThemeField_1.Field, { disabled: currentThemeIsReadOnly, key: field.name, type: field.type, name: field.name, value: valuesFromTheme[field.variable], variable: field.variable, onChange: (val) => {
                        // needs a fresh copy
                        const currentThemeObject = adaptable.api.themeApi.getCurrentThemeObject();
                        let newTheme = null;
                        if (val === false) {
                            newTheme = {
                                ...currentThemeObject,
                                CSSVariables: {
                                    ...currentThemeObject?.CSSVariables,
                                },
                            };
                            delete newTheme.CSSVariables[field.variable];
                        }
                        else {
                            newTheme = {
                                ...currentThemeObject,
                                CSSVariables: {
                                    ...currentThemeObject?.CSSVariables,
                                    [field.variable]: val,
                                },
                            };
                        }
                        setCurrentThemeObject(newTheme);
                        adaptable.api.themeApi.editTheme(newTheme);
                    } }));
            }))));
};
exports.ThemeEditor = ThemeEditor;
