var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "../cssLanguageTypes", "vscode-nls", "../parser/cssNodes", "../parser/cssSymbolScope", "../languageFacts/facts", "../utils/strings", "../utils/resources"], factory);
    }
})(function (require, exports) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CSSNavigation = void 0;
    var cssLanguageTypes_1 = require("../cssLanguageTypes");
    var nls = require("vscode-nls");
    var nodes = require("../parser/cssNodes");
    var cssSymbolScope_1 = require("../parser/cssSymbolScope");
    var facts_1 = require("../languageFacts/facts");
    var strings_1 = require("../utils/strings");
    var resources_1 = require("../utils/resources");
    var localize = nls.loadMessageBundle();
    var startsWithSchemeRegex = /^\w+:\/\//;
    var startsWithData = /^data:/;
    var CSSNavigation = /** @class */ (function () {
        function CSSNavigation(fileSystemProvider, resolveModuleReferences) {
            this.fileSystemProvider = fileSystemProvider;
            this.resolveModuleReferences = resolveModuleReferences;
        }
        CSSNavigation.prototype.findDefinition = function (document, position, stylesheet) {
            var symbols = new cssSymbolScope_1.Symbols(stylesheet);
            var offset = document.offsetAt(position);
            var node = nodes.getNodeAtOffset(stylesheet, offset);
            if (!node) {
                return null;
            }
            var symbol = symbols.findSymbolFromNode(node);
            if (!symbol) {
                return null;
            }
            return {
                uri: document.uri,
                range: getRange(symbol.node, document)
            };
        };
        CSSNavigation.prototype.findReferences = function (document, position, stylesheet) {
            var highlights = this.findDocumentHighlights(document, position, stylesheet);
            return highlights.map(function (h) {
                return {
                    uri: document.uri,
                    range: h.range
                };
            });
        };
        CSSNavigation.prototype.findDocumentHighlights = function (document, position, stylesheet) {
            var result = [];
            var offset = document.offsetAt(position);
            var node = nodes.getNodeAtOffset(stylesheet, offset);
            if (!node || node.type === nodes.NodeType.Stylesheet || node.type === nodes.NodeType.Declarations) {
                return result;
            }
            if (node.type === nodes.NodeType.Identifier && node.parent && node.parent.type === nodes.NodeType.ClassSelector) {
                node = node.parent;
            }
            var symbols = new cssSymbolScope_1.Symbols(stylesheet);
            var symbol = symbols.findSymbolFromNode(node);
            var name = node.getText();
            stylesheet.accept(function (candidate) {
                if (symbol) {
                    if (symbols.matchesSymbol(candidate, symbol)) {
                        result.push({
                            kind: getHighlightKind(candidate),
                            range: getRange(candidate, document)
                        });
                        return false;
                    }
                }
                else if (node && node.type === candidate.type && candidate.matches(name)) {
                    // Same node type and data
                    result.push({
                        kind: getHighlightKind(candidate),
                        range: getRange(candidate, document)
                    });
                }
                return true;
            });
            return result;
        };
        CSSNavigation.prototype.isRawStringDocumentLinkNode = function (node) {
            return node.type === nodes.NodeType.Import;
        };
        CSSNavigation.prototype.findDocumentLinks = function (document, stylesheet, documentContext) {
            var linkData = this.findUnresolvedLinks(document, stylesheet);
            var resolvedLinks = [];
            for (var _i = 0, linkData_1 = linkData; _i < linkData_1.length; _i++) {
                var data = linkData_1[_i];
                var link = data.link;
                var target = link.target;
                if (!target || startsWithData.test(target)) {
                    // no links for data:
                }
                else if (startsWithSchemeRegex.test(target)) {
                    resolvedLinks.push(link);
                }
                else {
                    var resolved = documentContext.resolveReference(target, document.uri);
                    if (resolved) {
                        link.target = resolved;
                    }
                    resolvedLinks.push(link);
                }
            }
            return resolvedLinks;
        };
        CSSNavigation.prototype.findDocumentLinks2 = function (document, stylesheet, documentContext) {
            return __awaiter(this, void 0, void 0, function () {
                var linkData, resolvedLinks, _i, linkData_2, data, link, target, resolvedTarget;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            linkData = this.findUnresolvedLinks(document, stylesheet);
                            resolvedLinks = [];
                            _i = 0, linkData_2 = linkData;
                            _a.label = 1;
                        case 1:
                            if (!(_i < linkData_2.length)) return [3 /*break*/, 6];
                            data = linkData_2[_i];
                            link = data.link;
                            target = link.target;
                            if (!(!target || startsWithData.test(target))) return [3 /*break*/, 2];
                            return [3 /*break*/, 5];
                        case 2:
                            if (!startsWithSchemeRegex.test(target)) return [3 /*break*/, 3];
                            resolvedLinks.push(link);
                            return [3 /*break*/, 5];
                        case 3: return [4 /*yield*/, this.resolveRelativeReference(target, document.uri, documentContext, data.isRawLink)];
                        case 4:
                            resolvedTarget = _a.sent();
                            if (resolvedTarget !== undefined) {
                                link.target = resolvedTarget;
                                resolvedLinks.push(link);
                            }
                            _a.label = 5;
                        case 5:
                            _i++;
                            return [3 /*break*/, 1];
                        case 6: return [2 /*return*/, resolvedLinks];
                    }
                });
            });
        };
        CSSNavigation.prototype.findUnresolvedLinks = function (document, stylesheet) {
            var _this = this;
            var result = [];
            var collect = function (uriStringNode) {
                var rawUri = uriStringNode.getText();
                var range = getRange(uriStringNode, document);
                // Make sure the range is not empty
                if (range.start.line === range.end.line && range.start.character === range.end.character) {
                    return;
                }
                if ((0, strings_1.startsWith)(rawUri, "'") || (0, strings_1.startsWith)(rawUri, "\"")) {
                    rawUri = rawUri.slice(1, -1);
                }
                var isRawLink = uriStringNode.parent ? _this.isRawStringDocumentLinkNode(uriStringNode.parent) : false;
                result.push({ link: { target: rawUri, range: range }, isRawLink: isRawLink });
            };
            stylesheet.accept(function (candidate) {
                if (candidate.type === nodes.NodeType.URILiteral) {
                    var first = candidate.getChild(0);
                    if (first) {
                        collect(first);
                    }
                    return false;
                }
                /**
                 * In @import, it is possible to include links that do not use `url()`
                 * For example, `@import 'foo.css';`
                 */
                if (candidate.parent && _this.isRawStringDocumentLinkNode(candidate.parent)) {
                    var rawText = candidate.getText();
                    if ((0, strings_1.startsWith)(rawText, "'") || (0, strings_1.startsWith)(rawText, "\"")) {
                        collect(candidate);
                    }
                    return false;
                }
                return true;
            });
            return result;
        };
        CSSNavigation.prototype.findDocumentSymbols = function (document, stylesheet) {
            var result = [];
            stylesheet.accept(function (node) {
                var entry = {
                    name: null,
                    kind: cssLanguageTypes_1.SymbolKind.Class,
                    location: null
                };
                var locationNode = node;
                if (node instanceof nodes.Selector) {
                    entry.name = node.getText();
                    locationNode = node.findAParent(nodes.NodeType.Ruleset, nodes.NodeType.ExtendsReference);
                    if (locationNode) {
                        entry.location = cssLanguageTypes_1.Location.create(document.uri, getRange(locationNode, document));
                        result.push(entry);
                    }
                    return false;
                }
                else if (node instanceof nodes.VariableDeclaration) {
                    entry.name = node.getName();
                    entry.kind = cssLanguageTypes_1.SymbolKind.Variable;
                }
                else if (node instanceof nodes.MixinDeclaration) {
                    entry.name = node.getName();
                    entry.kind = cssLanguageTypes_1.SymbolKind.Method;
                }
                else if (node instanceof nodes.FunctionDeclaration) {
                    entry.name = node.getName();
                    entry.kind = cssLanguageTypes_1.SymbolKind.Function;
                }
                else if (node instanceof nodes.Keyframe) {
                    entry.name = localize('literal.keyframes', "@keyframes {0}", node.getName());
                }
                else if (node instanceof nodes.FontFace) {
                    entry.name = localize('literal.fontface', "@font-face");
                }
                else if (node instanceof nodes.Media) {
                    var mediaList = node.getChild(0);
                    if (mediaList instanceof nodes.Medialist) {
                        entry.name = '@media ' + mediaList.getText();
                        entry.kind = cssLanguageTypes_1.SymbolKind.Module;
                    }
                }
                if (entry.name) {
                    entry.location = cssLanguageTypes_1.Location.create(document.uri, getRange(locationNode, document));
                    result.push(entry);
                }
                return true;
            });
            return result;
        };
        CSSNavigation.prototype.findDocumentColors = function (document, stylesheet) {
            var result = [];
            stylesheet.accept(function (node) {
                var colorInfo = getColorInformation(node, document);
                if (colorInfo) {
                    result.push(colorInfo);
                }
                return true;
            });
            return result;
        };
        CSSNavigation.prototype.getColorPresentations = function (document, stylesheet, color, range) {
            var result = [];
            var red256 = Math.round(color.red * 255), green256 = Math.round(color.green * 255), blue256 = Math.round(color.blue * 255);
            var label;
            if (color.alpha === 1) {
                label = "rgb(".concat(red256, ", ").concat(green256, ", ").concat(blue256, ")");
            }
            else {
                label = "rgba(".concat(red256, ", ").concat(green256, ", ").concat(blue256, ", ").concat(color.alpha, ")");
            }
            result.push({ label: label, textEdit: cssLanguageTypes_1.TextEdit.replace(range, label) });
            if (color.alpha === 1) {
                label = "#".concat(toTwoDigitHex(red256)).concat(toTwoDigitHex(green256)).concat(toTwoDigitHex(blue256));
            }
            else {
                label = "#".concat(toTwoDigitHex(red256)).concat(toTwoDigitHex(green256)).concat(toTwoDigitHex(blue256)).concat(toTwoDigitHex(Math.round(color.alpha * 255)));
            }
            result.push({ label: label, textEdit: cssLanguageTypes_1.TextEdit.replace(range, label) });
            var hsl = (0, facts_1.hslFromColor)(color);
            if (hsl.a === 1) {
                label = "hsl(".concat(hsl.h, ", ").concat(Math.round(hsl.s * 100), "%, ").concat(Math.round(hsl.l * 100), "%)");
            }
            else {
                label = "hsla(".concat(hsl.h, ", ").concat(Math.round(hsl.s * 100), "%, ").concat(Math.round(hsl.l * 100), "%, ").concat(hsl.a, ")");
            }
            result.push({ label: label, textEdit: cssLanguageTypes_1.TextEdit.replace(range, label) });
            var hwb = (0, facts_1.hwbFromColor)(color);
            if (hwb.a === 1) {
                label = "hwb(".concat(hwb.h, " ").concat(Math.round(hwb.w * 100), "% ").concat(Math.round(hwb.b * 100), "%)");
            }
            else {
                label = "hwb(".concat(hwb.h, " ").concat(Math.round(hwb.w * 100), "% ").concat(Math.round(hwb.b * 100), "% / ").concat(hwb.a, ")");
            }
            result.push({ label: label, textEdit: cssLanguageTypes_1.TextEdit.replace(range, label) });
            return result;
        };
        CSSNavigation.prototype.doRename = function (document, position, newName, stylesheet) {
            var _a;
            var highlights = this.findDocumentHighlights(document, position, stylesheet);
            var edits = highlights.map(function (h) { return cssLanguageTypes_1.TextEdit.replace(h.range, newName); });
            return {
                changes: (_a = {}, _a[document.uri] = edits, _a)
            };
        };
        CSSNavigation.prototype.resolveModuleReference = function (ref, documentUri, documentContext) {
            return __awaiter(this, void 0, void 0, function () {
                var moduleName, rootFolderUri, documentFolderUri, modulePath, pathWithinModule;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!(0, strings_1.startsWith)(documentUri, 'file://')) return [3 /*break*/, 2];
                            moduleName = getModuleNameFromPath(ref);
                            rootFolderUri = documentContext.resolveReference('/', documentUri);
                            documentFolderUri = (0, resources_1.dirname)(documentUri);
                            return [4 /*yield*/, this.resolvePathToModule(moduleName, documentFolderUri, rootFolderUri)];
                        case 1:
                            modulePath = _a.sent();
                            if (modulePath) {
                                pathWithinModule = ref.substring(moduleName.length + 1);
                                return [2 /*return*/, (0, resources_1.joinPath)(modulePath, pathWithinModule)];
                            }
                            _a.label = 2;
                        case 2: return [2 /*return*/, undefined];
                    }
                });
            });
        };
        CSSNavigation.prototype.resolveRelativeReference = function (ref, documentUri, documentContext, isRawLink) {
            return __awaiter(this, void 0, void 0, function () {
                var relativeReference, _a;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            relativeReference = documentContext.resolveReference(ref, documentUri);
                            if (!(ref[0] === '~' && ref[1] !== '/' && this.fileSystemProvider)) return [3 /*break*/, 2];
                            ref = ref.substring(1);
                            return [4 /*yield*/, this.resolveModuleReference(ref, documentUri, documentContext)];
                        case 1: return [2 /*return*/, (_b.sent()) || relativeReference];
                        case 2:
                            if (!this.resolveModuleReferences) return [3 /*break*/, 7];
                            _a = relativeReference;
                            if (!_a) return [3 /*break*/, 4];
                            return [4 /*yield*/, this.fileExists(relativeReference)];
                        case 3:
                            _a = (_b.sent());
                            _b.label = 4;
                        case 4:
                            if (!_a) return [3 /*break*/, 5];
                            return [2 /*return*/, relativeReference];
                        case 5: return [4 /*yield*/, this.resolveModuleReference(ref, documentUri, documentContext)];
                        case 6: return [2 /*return*/, (_b.sent()) || relativeReference];
                        case 7: return [2 /*return*/, relativeReference];
                    }
                });
            });
        };
        CSSNavigation.prototype.resolvePathToModule = function (_moduleName, documentFolderUri, rootFolderUri) {
            return __awaiter(this, void 0, void 0, function () {
                var packPath;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            packPath = (0, resources_1.joinPath)(documentFolderUri, 'node_modules', _moduleName, 'package.json');
                            return [4 /*yield*/, this.fileExists(packPath)];
                        case 1:
                            if (_a.sent()) {
                                return [2 /*return*/, (0, resources_1.dirname)(packPath)];
                            }
                            else if (rootFolderUri && documentFolderUri.startsWith(rootFolderUri) && (documentFolderUri.length !== rootFolderUri.length)) {
                                return [2 /*return*/, this.resolvePathToModule(_moduleName, (0, resources_1.dirname)(documentFolderUri), rootFolderUri)];
                            }
                            return [2 /*return*/, undefined];
                    }
                });
            });
        };
        CSSNavigation.prototype.fileExists = function (uri) {
            return __awaiter(this, void 0, void 0, function () {
                var stat, err_1;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.fileSystemProvider) {
                                return [2 /*return*/, false];
                            }
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 3, , 4]);
                            return [4 /*yield*/, this.fileSystemProvider.stat(uri)];
                        case 2:
                            stat = _a.sent();
                            if (stat.type === cssLanguageTypes_1.FileType.Unknown && stat.size === -1) {
                                return [2 /*return*/, false];
                            }
                            return [2 /*return*/, true];
                        case 3:
                            err_1 = _a.sent();
                            return [2 /*return*/, false];
                        case 4: return [2 /*return*/];
                    }
                });
            });
        };
        return CSSNavigation;
    }());
    exports.CSSNavigation = CSSNavigation;
    function getColorInformation(node, document) {
        var color = (0, facts_1.getColorValue)(node);
        if (color) {
            var range = getRange(node, document);
            return { color: color, range: range };
        }
        return null;
    }
    function getRange(node, document) {
        return cssLanguageTypes_1.Range.create(document.positionAt(node.offset), document.positionAt(node.end));
    }
    function getHighlightKind(node) {
        if (node.type === nodes.NodeType.Selector) {
            return cssLanguageTypes_1.DocumentHighlightKind.Write;
        }
        if (node instanceof nodes.Identifier) {
            if (node.parent && node.parent instanceof nodes.Property) {
                if (node.isCustomProperty) {
                    return cssLanguageTypes_1.DocumentHighlightKind.Write;
                }
            }
        }
        if (node.parent) {
            switch (node.parent.type) {
                case nodes.NodeType.FunctionDeclaration:
                case nodes.NodeType.MixinDeclaration:
                case nodes.NodeType.Keyframe:
                case nodes.NodeType.VariableDeclaration:
                case nodes.NodeType.FunctionParameter:
                    return cssLanguageTypes_1.DocumentHighlightKind.Write;
            }
        }
        return cssLanguageTypes_1.DocumentHighlightKind.Read;
    }
    function toTwoDigitHex(n) {
        var r = n.toString(16);
        return r.length !== 2 ? '0' + r : r;
    }
    function getModuleNameFromPath(path) {
        // If a scoped module (starts with @) then get up until second instance of '/', otherwise get until first instance of '/'
        if (path[0] === '@') {
            return path.substring(0, path.indexOf('/', path.indexOf('/') + 1));
        }
        return path.substring(0, path.indexOf('/'));
    }
});
