// #region Imports
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { CssLength, ITheme, IThemePalette } from '@breadstone/mosaik-themes';
import { Component } from '../Controls/Decorators/ComponentDecorator';
import { CustomElement } from '../Controls/Components/Abstracts/CustomElement';
import { theme2ElementTemplate } from './Theme2ElementTemplate';
import { theme2ElementStyle } from './Theme2ElementStyle';
import { Property } from '../Controls/Decorators/PropertyDecorator';
import { Watch } from '../Controls/Decorators/WatchDecorator';
import { RendererServiceLocator } from '../Dom/Renderer';
import { Equals } from '../Equality/Equals';
import { Theme2 } from './Theme2';
import { GlobalStyleSheet } from '../Dom/StyleSheet';
// #endregion
/**
 * The `{@link Theme2Element}` element.
 *
 * @public
 */
let Theme2Element = class Theme2Element extends CustomElement {
    // #region Fields
    _theme;
    _isInline;
    _globalStyleSheet;
    // #endregion
    // #region Ctor
    /**
     * @public
     */
    constructor() {
        super();
        Theme2.register(this);
        this._theme = null;
        this._isInline = false;
        this._globalStyleSheet = new GlobalStyleSheet();
    }
    // #endregion
    // #region Properties
    /**
     * Returns the `{@link is}` property.
     * The `{@link is}` property represents natural name of this element.
     *
     * @public
     * @static
     * @readonly
     */
    static get is() {
        return 'mosaik-theme2';
    }
    // #endregion
    // #region Properties
    /**
     * Gets or sets the `theme` property.
     *
     * @public
     */
    get theme() {
        return this._theme;
    }
    set theme(value) {
        if (!Equals.areObjectsEqual(this._theme, value)) {
            // if (value) {
            //     value = Observable.observe(value, (next) => {
            //         this.applyTheme(next);
            //     });
            // }
            this._theme = value;
            this.requestUpdate('theme');
        }
    }
    /**
     * Gets or sets the `isInline` property.
     *
     * @public
     */
    get isInline() {
        return this._isInline;
    }
    set isInline(value) {
        if (this._isInline !== value) {
            this._isInline = value;
            this.requestUpdate('isInline');
        }
    }
    // #endregion
    // #region Methods
    /**
     * @public
     * @override
     */
    connectedCallback() {
        super.connectedCallback();
        this._globalStyleSheet.initialize();
        this.applyTheme(this._theme);
    }
    /**
     * @public
     * @override
     */
    disconnectedCallback() {
        Theme2.unregister(this);
        this._globalStyleSheet.dispose();
    }
    /**
     * @internal
     */
    applyScheme(theme) {
        const themeName = this._theme?.name ?? '';
        const variables = new Map();
        Object.entries(theme).forEach(([key, value]) => {
            Object.entries(value).forEach(([k, v]) => {
                k = k.replace(/([a-z])([A-Z])/g, '$1-$2').replace(/\s+/g, '-')
                    .toLowerCase();
                variables.set(`--${themeName}-scheme-${key}-${k}`, v);
            });
        });
        variables.forEach((v, k) => {
            RendererServiceLocator.current.setStyle(this, k, v);
            this.setGlobalVariable(k, v);
        });
    }
    /**
     * @internal
     */
    applyPalette(palette) {
        const themeName = this._theme?.name ?? '';
        const variables = new Map();
        Object.entries(palette).forEach(([mode, modeValues]) => {
            Object.entries(modeValues).forEach(([modePalette, modePaletteValues]) => {
                if (!IThemePalette.isThemePalette(modePaletteValues)) {
                    variables.set(`--${themeName}-color-${mode}-${modePalette}`, modePaletteValues);
                    return;
                }
                Object.entries(modePaletteValues).forEach(([k, v]) => {
                    k = k.replace(/([a-z])([A-Z])/g, '$1-$2').replace(/\s+/g, '-')
                        .toLowerCase();
                    variables.set(`--${themeName}-color-${mode}-${modePalette}-${k}`, v);
                });
            });
        });
        variables.forEach((v, k) => {
            RendererServiceLocator.current.setStyle(this, k, v);
            this.setGlobalVariable(k, v);
        });
    }
    /**
     * @internal
     */
    applyFontFamily(fontFamily) {
        const themeName = this._theme?.name ?? '';
        const typos = Object.keys(this._theme?.typography ?? {});
        RendererServiceLocator.current.setStyle(this, `--${themeName}-font-family`, fontFamily);
        this.setGlobalVariable(`--${themeName}-font-family`, fontFamily);
        typos.forEach((x) => {
            RendererServiceLocator.current.setStyle(this, `--${themeName}-typography-${x}-font-family`, fontFamily);
            this.setGlobalVariable(`--${themeName}-typography-${x}-font-family`, fontFamily);
        });
    }
    /**
     * @internal
     */
    applyTypography(typography) {
        const themeName = this._theme?.name ?? '';
        const themeFontFamily = this._theme?.fontFamily ?? '';
        Object.entries(typography).forEach(([name, value]) => {
            Object.entries(value).forEach(([key, v]) => {
                key = key.replace(/([a-z])([A-Z])/g, '$1-$2').replace(/\s+/g, '-')
                    .toLowerCase();
                RendererServiceLocator.current.setStyle(this, `--${themeName}-typography-${name}-${key}`, v);
                this.setGlobalVariable(`--${themeName}-typography-${name}-${key}`, v);
            });
            RendererServiceLocator.current.setStyle(this, `--${themeName}-typography-${name}`, `${value.fontWeight} ${value.fontSize}/${value.lineHeight} ${themeFontFamily}`);
            this.setGlobalVariable(`--${themeName}-typography-${name}`, `${value.fontWeight} ${value.fontSize}/${value.lineHeight} ${themeFontFamily}`);
        });
    }
    /**
     * @internal
     */
    applyLayout(layout) {
        const themeName = this._theme?.name ?? '';
        // Validate that each property in newValue is a px value.
        Object.values(layout).forEach((x) => {
            if (typeof x === 'number') {
                x = `${x}px`;
            }
            else if (x === 'auto') {
                throw new Error(`[Theme2Element] The layout property '${x}' must be a px value.`);
            }
            else if (CssLength.extractUnit(x) !== 'px') {
                throw new Error(`[Theme2Element] The layout property '${x}' must be a px value.`);
            }
        });
        Object.entries(layout).forEach(([key, value]) => {
            key = key.replace(/([a-z])([A-Z])/g, '$1-$2').replace(/\s+/g, '-')
                .toLowerCase();
            value = typeof value === 'number' ? `${value}px` : value;
            RendererServiceLocator.current.setStyle(this, `--${themeName}-layout-${key}`, value);
            this.setGlobalVariable(`--${themeName}-layout-${key}`, value);
        });
    }
    /**
     * @internal
     */
    applyElevation(elevation) {
        const themeName = this._theme?.name ?? '';
        Object.entries(elevation).forEach(([key, value]) => {
            Object.entries(value).forEach(([k, v]) => {
                k = k.replace(/([a-z])([A-Z])/g, '$1-$2').replace(/\s+/g, '-')
                    .toLowerCase();
                // RendererServiceLocator.current.setStyle(this, `--${themeName}-elevation-${key}-${k}`, v);
                // this.setGlobalVariable(`--${themeName}-elevation-${key}-${k}`, v);
            });
        });
    }
    /**
     * @protected
     */
    onThemePropertyChanged(prev, next) {
        if (prev !== next && next) {
            this.applyTheme(next);
        }
    }
    /**
     * @private
     */
    setGlobalVariable(property, value) {
        this._globalStyleSheet.setVariable(property, value);
        document.documentElement.style.setProperty(property, value);
    }
    /**
     * @private
     */
    applyTheme(theme) {
        if (!theme) {
            return;
        }
        this.applyScheme(theme.scheme);
        this.applyPalette(theme.palette);
        this.applyFontFamily(theme.fontFamily);
        this.applyTypography(theme.typography);
        this.applyLayout(theme.layout);
        this.applyElevation(theme.elevation);
    }
};
__decorate([
    Property({ type: Object }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [Object])
], Theme2Element.prototype, "theme", null);
__decorate([
    Property({ type: Boolean }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], Theme2Element.prototype, "isInline", null);
__decorate([
    Watch('theme'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", void 0)
], Theme2Element.prototype, "onThemePropertyChanged", null);
Theme2Element = __decorate([
    Component({
        selector: 'mosaik-theme2',
        template: theme2ElementTemplate,
        styles: theme2ElementStyle,
        imports: []
    }),
    __metadata("design:paramtypes", [])
], Theme2Element);
export { Theme2Element };
//# sourceMappingURL=Theme2Element.js.map