import * as i0 from '@angular/core';
import { InjectionToken, Injectable, Optional, Inject } from '@angular/core';
import { Subject } from 'rxjs';
import { filter, mapTo } from 'rxjs/operators';
import { TinyColor } from '@ctrl/tinycolor';
import { generate } from 'ng-zorro-antd/core/color';
import { warn } from 'ng-zorro-antd/core/logger';
import { canUseDom, updateCSS } from 'ng-zorro-antd/core/util';

/**
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/LICENSE
 */
/**
 * User should provide an object implements this interface to set global configurations.
 */
const NZ_CONFIG = new InjectionToken('nz-config');

/**
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/LICENSE
 */
const dynamicStyleMark = `-ant-${Date.now()}-${Math.random()}`;
function getStyle(globalPrefixCls, theme) {
    const variables = {};
    const formatColor = (color, updater) => {
        let clone = color.clone();
        clone = updater?.(clone) || clone;
        return clone.toRgbString();
    };
    const fillColor = (colorVal, type) => {
        const baseColor = new TinyColor(colorVal);
        const colorPalettes = generate(baseColor.toRgbString());
        variables[`${type}-color`] = formatColor(baseColor);
        variables[`${type}-color-disabled`] = colorPalettes[1];
        variables[`${type}-color-hover`] = colorPalettes[4];
        variables[`${type}-color-active`] = colorPalettes[7];
        variables[`${type}-color-outline`] = baseColor.clone().setAlpha(0.2).toRgbString();
        variables[`${type}-color-deprecated-bg`] = colorPalettes[1];
        variables[`${type}-color-deprecated-border`] = colorPalettes[3];
    };
    // ================ Primary Color ================
    if (theme.primaryColor) {
        fillColor(theme.primaryColor, 'primary');
        const primaryColor = new TinyColor(theme.primaryColor);
        const primaryColors = generate(primaryColor.toRgbString());
        // Legacy - We should use semantic naming standard
        primaryColors.forEach((color, index) => {
            variables[`primary-${index + 1}`] = color;
        });
        // Deprecated
        variables['primary-color-deprecated-l-35'] = formatColor(primaryColor, c => c.lighten(35));
        variables['primary-color-deprecated-l-20'] = formatColor(primaryColor, c => c.lighten(20));
        variables['primary-color-deprecated-t-20'] = formatColor(primaryColor, c => c.tint(20));
        variables['primary-color-deprecated-t-50'] = formatColor(primaryColor, c => c.tint(50));
        variables['primary-color-deprecated-f-12'] = formatColor(primaryColor, c => c.setAlpha(c.getAlpha() * 0.12));
        const primaryActiveColor = new TinyColor(primaryColors[0]);
        variables['primary-color-active-deprecated-f-30'] = formatColor(primaryActiveColor, c => c.setAlpha(c.getAlpha() * 0.3));
        variables['primary-color-active-deprecated-d-02'] = formatColor(primaryActiveColor, c => c.darken(2));
    }
    // ================ Success Color ================
    if (theme.successColor) {
        fillColor(theme.successColor, 'success');
    }
    // ================ Warning Color ================
    if (theme.warningColor) {
        fillColor(theme.warningColor, 'warning');
    }
    // ================= Error Color =================
    if (theme.errorColor) {
        fillColor(theme.errorColor, 'error');
    }
    // ================= Info Color ==================
    if (theme.infoColor) {
        fillColor(theme.infoColor, 'info');
    }
    // Convert to css variables
    const cssList = Object.keys(variables).map(key => `--${globalPrefixCls}-${key}: ${variables[key]};`);
    return `
  :root {
    ${cssList.join('\n')}
  }
  `.trim();
}
function registerTheme(globalPrefixCls, theme) {
    const style = getStyle(globalPrefixCls, theme);
    if (canUseDom()) {
        updateCSS(style, `${dynamicStyleMark}-dynamic-theme`);
    }
    else {
        warn(`NzConfigService: SSR do not support dynamic theme with css variables.`);
    }
}

/**
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/LICENSE
 */
const isDefined = function (value) {
    return value !== undefined;
};
const defaultPrefixCls = 'ant';
class NzConfigService {
    constructor(defaultConfig) {
        this.configUpdated$ = new Subject();
        this.config = defaultConfig || {};
        if (this.config.theme) {
            // If theme is set with NZ_CONFIG, register theme to make sure css variables work
            registerTheme(this.getConfig().prefixCls?.prefixCls || defaultPrefixCls, this.config.theme);
        }
    }
    getConfig() {
        return this.config;
    }
    getConfigForComponent(componentName) {
        return this.config[componentName];
    }
    getConfigChangeEventForComponent(componentName) {
        return this.configUpdated$.pipe(filter(n => n === componentName), mapTo(undefined));
    }
    set(componentName, value) {
        this.config[componentName] = { ...this.config[componentName], ...value };
        if (componentName === 'theme' && this.config.theme) {
            registerTheme(this.getConfig().prefixCls?.prefixCls || defaultPrefixCls, this.config.theme);
        }
        this.configUpdated$.next(componentName);
    }
}
NzConfigService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.0.3", ngImport: i0, type: NzConfigService, deps: [{ token: NZ_CONFIG, optional: true }], target: i0.ɵɵFactoryTarget.Injectable });
NzConfigService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.0.3", ngImport: i0, type: NzConfigService, providedIn: 'root' });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.0.3", ngImport: i0, type: NzConfigService, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root'
                }]
        }], ctorParameters: function () { return [{ type: undefined, decorators: [{
                    type: Optional
                }, {
                    type: Inject,
                    args: [NZ_CONFIG]
                }] }]; } });
/* eslint-disable no-invalid-this */
/**
 * This decorator is used to decorate properties. If a property is decorated, it would try to load default value from
 * config.
 */
// eslint-disable-next-line
function WithConfig() {
    return function ConfigDecorator(target, propName, originalDescriptor) {
        const privatePropName = `$$__zorroConfigDecorator__${propName}`;
        Object.defineProperty(target, privatePropName, {
            configurable: true,
            writable: true,
            enumerable: false
        });
        return {
            get() {
                const originalValue = originalDescriptor?.get ? originalDescriptor.get.bind(this)() : this[privatePropName];
                const assignedByUser = (this.propertyAssignCounter?.[propName] || 0) > 1;
                const configValue = this.nzConfigService.getConfigForComponent(this._nzModuleName)?.[propName];
                if (assignedByUser && isDefined(originalValue)) {
                    return originalValue;
                }
                else {
                    return isDefined(configValue) ? configValue : originalValue;
                }
            },
            set(value) {
                // If the value is assigned, we consider the newly assigned value as 'assigned by user'.
                this.propertyAssignCounter = this.propertyAssignCounter || {};
                this.propertyAssignCounter[propName] = (this.propertyAssignCounter[propName] || 0) + 1;
                if (originalDescriptor?.set) {
                    originalDescriptor.set.bind(this)(value);
                }
                else {
                    this[privatePropName] = value;
                }
            },
            configurable: true,
            enumerable: true
        };
    };
}

/**
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/LICENSE
 */

/**
 * Generated bundle index. Do not edit.
 */

export { NZ_CONFIG, NzConfigService, WithConfig, getStyle, registerTheme };
//# sourceMappingURL=ng-zorro-antd-core-config.mjs.map
