/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
import { distinct } from '../../../base/common/arrays.js';
import { Emitter } from '../../../base/common/event.js';
import * as types from '../../../base/common/types.js';
import * as nls from '../../../nls.js';
import { Extensions as JSONExtensions } from '../../jsonschemas/common/jsonContributionRegistry.js';
import { Registry } from '../../registry/common/platform.js';
export var EditPresentationTypes;
(function (EditPresentationTypes) {
    EditPresentationTypes["Multiline"] = "multilineText";
    EditPresentationTypes["Singleline"] = "singlelineText";
})(EditPresentationTypes || (EditPresentationTypes = {}));
export const Extensions = {
    Configuration: 'base.contributions.configuration'
};
export const allSettings = { properties: {}, patternProperties: {} };
export const applicationSettings = { properties: {}, patternProperties: {} };
export const machineSettings = { properties: {}, patternProperties: {} };
export const machineOverridableSettings = { properties: {}, patternProperties: {} };
export const windowSettings = { properties: {}, patternProperties: {} };
export const resourceSettings = { properties: {}, patternProperties: {} };
export const resourceLanguageSettingsSchemaId = 'vscode://schemas/settings/resourceLanguage';
const contributionRegistry = Registry.as(JSONExtensions.JSONContribution);
class ConfigurationRegistry {
    constructor() {
        this.overrideIdentifiers = new Set();
        this._onDidSchemaChange = new Emitter();
        this.onDidSchemaChange = this._onDidSchemaChange.event;
        this._onDidUpdateConfiguration = new Emitter();
        this.onDidUpdateConfiguration = this._onDidUpdateConfiguration.event;
        this.defaultValues = {};
        this.defaultLanguageConfigurationOverridesNode = {
            id: 'defaultOverrides',
            title: nls.localize('defaultLanguageConfigurationOverrides.title', "Default Language Configuration Overrides"),
            properties: {}
        };
        this.configurationContributors = [this.defaultLanguageConfigurationOverridesNode];
        this.resourceLanguageSettingsSchema = { properties: {}, patternProperties: {}, additionalProperties: false, errorMessage: 'Unknown editor configuration setting', allowTrailingCommas: true, allowComments: true };
        this.configurationProperties = {};
        this.excludedConfigurationProperties = {};
        contributionRegistry.registerSchema(resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
    }
    registerConfiguration(configuration, validate = true) {
        this.registerConfigurations([configuration], validate);
    }
    registerConfigurations(configurations, validate = true) {
        const properties = this.doRegisterConfigurations(configurations, validate);
        contributionRegistry.registerSchema(resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
        this._onDidSchemaChange.fire();
        this._onDidUpdateConfiguration.fire(properties);
    }
    deregisterConfigurations(configurations) {
        const properties = this.doDeregisterConfigurations(configurations);
        contributionRegistry.registerSchema(resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
        this._onDidSchemaChange.fire();
        this._onDidUpdateConfiguration.fire(properties);
    }
    updateConfigurations({ add, remove }) {
        const properties = [];
        properties.push(...this.doDeregisterConfigurations(remove));
        properties.push(...this.doRegisterConfigurations(add, false));
        contributionRegistry.registerSchema(resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
        this._onDidSchemaChange.fire();
        this._onDidUpdateConfiguration.fire(distinct(properties));
    }
    registerDefaultConfigurations(defaultConfigurations) {
        const properties = [];
        const overrideIdentifiers = [];
        for (const defaultConfiguration of defaultConfigurations) {
            for (const key in defaultConfiguration) {
                properties.push(key);
                if (OVERRIDE_PROPERTY_PATTERN.test(key)) {
                    this.defaultValues[key] = Object.assign(Object.assign({}, (this.defaultValues[key] || {})), defaultConfiguration[key]);
                    const property = {
                        type: 'object',
                        default: this.defaultValues[key],
                        description: nls.localize('defaultLanguageConfiguration.description', "Configure settings to be overridden for {0} language.", key),
                        $ref: resourceLanguageSettingsSchemaId
                    };
                    overrideIdentifiers.push(overrideIdentifierFromKey(key));
                    this.configurationProperties[key] = property;
                    this.defaultLanguageConfigurationOverridesNode.properties[key] = property;
                }
                else {
                    this.defaultValues[key] = defaultConfiguration[key];
                    const property = this.configurationProperties[key];
                    if (property) {
                        this.updatePropertyDefaultValue(key, property);
                        this.updateSchema(key, property);
                    }
                }
            }
        }
        this.registerOverrideIdentifiers(overrideIdentifiers);
        this._onDidSchemaChange.fire();
        this._onDidUpdateConfiguration.fire(properties);
    }
    deregisterDefaultConfigurations(defaultConfigurations) {
        const properties = [];
        for (const defaultConfiguration of defaultConfigurations) {
            for (const key in defaultConfiguration) {
                properties.push(key);
                delete this.defaultValues[key];
                if (OVERRIDE_PROPERTY_PATTERN.test(key)) {
                    delete this.configurationProperties[key];
                    delete this.defaultLanguageConfigurationOverridesNode.properties[key];
                }
                else {
                    const property = this.configurationProperties[key];
                    if (property) {
                        this.updatePropertyDefaultValue(key, property);
                        this.updateSchema(key, property);
                    }
                }
            }
        }
        this.updateOverridePropertyPatternKey();
        this._onDidSchemaChange.fire();
        this._onDidUpdateConfiguration.fire(properties);
    }
    notifyConfigurationSchemaUpdated(...configurations) {
        this._onDidSchemaChange.fire();
    }
    registerOverrideIdentifiers(overrideIdentifiers) {
        for (const overrideIdentifier of overrideIdentifiers) {
            this.overrideIdentifiers.add(overrideIdentifier);
        }
        this.updateOverridePropertyPatternKey();
    }
    doRegisterConfigurations(configurations, validate) {
        const properties = [];
        configurations.forEach(configuration => {
            properties.push(...this.validateAndRegisterProperties(configuration, validate, configuration.extensionInfo)); // fills in defaults
            this.configurationContributors.push(configuration);
            this.registerJSONConfiguration(configuration);
        });
        return properties;
    }
    doDeregisterConfigurations(configurations) {
        const properties = [];
        const deregisterConfiguration = (configuration) => {
            if (configuration.properties) {
                for (const key in configuration.properties) {
                    properties.push(key);
                    delete this.configurationProperties[key];
                    this.removeFromSchema(key, configuration.properties[key]);
                }
            }
            if (configuration.allOf) {
                configuration.allOf.forEach(node => deregisterConfiguration(node));
            }
        };
        for (const configuration of configurations) {
            deregisterConfiguration(configuration);
            const index = this.configurationContributors.indexOf(configuration);
            if (index !== -1) {
                this.configurationContributors.splice(index, 1);
            }
        }
        return properties;
    }
    validateAndRegisterProperties(configuration, validate = true, extensionInfo, scope = 3 /* WINDOW */) {
        var _a;
        scope = types.isUndefinedOrNull(configuration.scope) ? scope : configuration.scope;
        let propertyKeys = [];
        let properties = configuration.properties;
        if (properties) {
            for (let key in properties) {
                if (validate && validateProperty(key)) {
                    delete properties[key];
                    continue;
                }
                const property = properties[key];
                // update default value
                this.updatePropertyDefaultValue(key, property);
                // update scope
                if (OVERRIDE_PROPERTY_PATTERN.test(key)) {
                    property.scope = undefined; // No scope for overridable properties `[${identifier}]`
                }
                else {
                    property.scope = types.isUndefinedOrNull(property.scope) ? scope : property.scope;
                    property.restricted = types.isUndefinedOrNull(property.restricted) ? !!((_a = extensionInfo === null || extensionInfo === void 0 ? void 0 : extensionInfo.restrictedConfigurations) === null || _a === void 0 ? void 0 : _a.includes(key)) : property.restricted;
                }
                // Add to properties maps
                // Property is included by default if 'included' is unspecified
                if (properties[key].hasOwnProperty('included') && !properties[key].included) {
                    this.excludedConfigurationProperties[key] = properties[key];
                    delete properties[key];
                    continue;
                }
                else {
                    this.configurationProperties[key] = properties[key];
                }
                if (!properties[key].deprecationMessage && properties[key].markdownDeprecationMessage) {
                    // If not set, default deprecationMessage to the markdown source
                    properties[key].deprecationMessage = properties[key].markdownDeprecationMessage;
                }
                propertyKeys.push(key);
            }
        }
        let subNodes = configuration.allOf;
        if (subNodes) {
            for (let node of subNodes) {
                propertyKeys.push(...this.validateAndRegisterProperties(node, validate, extensionInfo, scope));
            }
        }
        return propertyKeys;
    }
    getConfigurations() {
        return this.configurationContributors;
    }
    getConfigurationProperties() {
        return this.configurationProperties;
    }
    getExcludedConfigurationProperties() {
        return this.excludedConfigurationProperties;
    }
    registerJSONConfiguration(configuration) {
        const register = (configuration) => {
            let properties = configuration.properties;
            if (properties) {
                for (const key in properties) {
                    this.updateSchema(key, properties[key]);
                }
            }
            let subNodes = configuration.allOf;
            if (subNodes) {
                subNodes.forEach(register);
            }
        };
        register(configuration);
    }
    updateSchema(key, property) {
        allSettings.properties[key] = property;
        switch (property.scope) {
            case 1 /* APPLICATION */:
                applicationSettings.properties[key] = property;
                break;
            case 2 /* MACHINE */:
                machineSettings.properties[key] = property;
                break;
            case 6 /* MACHINE_OVERRIDABLE */:
                machineOverridableSettings.properties[key] = property;
                break;
            case 3 /* WINDOW */:
                windowSettings.properties[key] = property;
                break;
            case 4 /* RESOURCE */:
                resourceSettings.properties[key] = property;
                break;
            case 5 /* LANGUAGE_OVERRIDABLE */:
                resourceSettings.properties[key] = property;
                this.resourceLanguageSettingsSchema.properties[key] = property;
                break;
        }
    }
    removeFromSchema(key, property) {
        delete allSettings.properties[key];
        switch (property.scope) {
            case 1 /* APPLICATION */:
                delete applicationSettings.properties[key];
                break;
            case 2 /* MACHINE */:
                delete machineSettings.properties[key];
                break;
            case 6 /* MACHINE_OVERRIDABLE */:
                delete machineOverridableSettings.properties[key];
                break;
            case 3 /* WINDOW */:
                delete windowSettings.properties[key];
                break;
            case 4 /* RESOURCE */:
            case 5 /* LANGUAGE_OVERRIDABLE */:
                delete resourceSettings.properties[key];
                break;
        }
    }
    updateOverridePropertyPatternKey() {
        for (const overrideIdentifier of this.overrideIdentifiers.values()) {
            const overrideIdentifierProperty = `[${overrideIdentifier}]`;
            const resourceLanguagePropertiesSchema = {
                type: 'object',
                description: nls.localize('overrideSettings.defaultDescription', "Configure editor settings to be overridden for a language."),
                errorMessage: nls.localize('overrideSettings.errorMessage', "This setting does not support per-language configuration."),
                $ref: resourceLanguageSettingsSchemaId,
            };
            this.updatePropertyDefaultValue(overrideIdentifierProperty, resourceLanguagePropertiesSchema);
            allSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
            applicationSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
            machineSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
            machineOverridableSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
            windowSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
            resourceSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
        }
        this._onDidSchemaChange.fire();
    }
    updatePropertyDefaultValue(key, property) {
        let defaultValue = this.defaultValues[key];
        if (types.isUndefined(defaultValue)) {
            defaultValue = property.default;
        }
        if (types.isUndefined(defaultValue)) {
            defaultValue = getDefaultValue(property.type);
        }
        property.default = defaultValue;
    }
}
const OVERRIDE_PROPERTY = '\\[.*\\]$';
export const OVERRIDE_PROPERTY_PATTERN = new RegExp(OVERRIDE_PROPERTY);
export function overrideIdentifierFromKey(key) {
    return key.substring(1, key.length - 1);
}
export function getDefaultValue(type) {
    const t = Array.isArray(type) ? type[0] : type;
    switch (t) {
        case 'boolean':
            return false;
        case 'integer':
        case 'number':
            return 0;
        case 'string':
            return '';
        case 'array':
            return [];
        case 'object':
            return {};
        default:
            return null;
    }
}
const configurationRegistry = new ConfigurationRegistry();
Registry.add(Extensions.Configuration, configurationRegistry);
export function validateProperty(property) {
    if (!property.trim()) {
        return nls.localize('config.property.empty', "Cannot register an empty property");
    }
    if (OVERRIDE_PROPERTY_PATTERN.test(property)) {
        return nls.localize('config.property.languageDefault', "Cannot register '{0}'. This matches property pattern '\\\\[.*\\\\]$' for describing language specific editor settings. Use 'configurationDefaults' contribution.", property);
    }
    if (configurationRegistry.getConfigurationProperties()[property] !== undefined) {
        return nls.localize('config.property.duplicate', "Cannot register '{0}'. This property is already registered.", property);
    }
    return null;
}
