"use strict";
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 __asyncValues = (this && this.__asyncValues) || function (o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fast_glob_1 = __importDefault(require("fast-glob"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const _directorys_1 = __importDefault(require("../utils/_directorys"));
/**
 * Creates a style sheet based on the fileKey, if it's a section or layout it will wrap in {% style %} tags, otherwise <style> tags.
 * @param content - a Buffer from FS to be passed, this is the inital content before replacing with the inline style.
 * @param fileKey - a String to be passed, this is the file name with the base directory.
 */
const createStyleSheet = (content, fileKey) => {
    const styleStartTags = (fileKey.includes('section/') || fileKey.includes('layout/')) ? '{% style %}' : '<style>';
    const styleEndTags = (fileKey.includes('section/') || fileKey.includes('layout/')) ? '{% endstyle %}' : '</style>';
    return `${styleStartTags}
    ${content.toString()}
  ${styleEndTags}`;
};
/**
 * Inserts a stylesheet into the file in the dist directory.
 * @param fileKey - a String to be passed with base directory & file name.
 * @param fileContents - contents of the file.
 * @param stylesheetFile - The linked stylesheet file to be used.
 * @param templateString - the string to be replaced, usually <!--mango-link: something/mango.something.css-->
 */
const insertStyleSheet = (fileKey, fileContents, templateString) => { var templateString_1, templateString_1_1; return __awaiter(void 0, void 0, void 0, function* () {
    var e_1, _a;
    let newFileContents = fileContents;
    try {
        for (templateString_1 = __asyncValues(templateString); templateString_1_1 = yield templateString_1.next(), !templateString_1_1.done;) {
            const match = templateString_1_1.value;
            const stylesheetFile = match.match(/<!--mango-link:(.*?)-->/)[1].trim();
            const styleSheet = yield fs_extra_1.default.readFile(`${_directorys_1.default.distAssetsRoot}/${stylesheetFile}`);
            const styleSheetContent = createStyleSheet(styleSheet, fileKey);
            newFileContents = newFileContents.replace(match, styleSheetContent);
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (templateString_1_1 && !templateString_1_1.done && (_a = templateString_1.return)) yield _a.call(templateString_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    yield fs_extra_1.default.writeFile(fileKey, newFileContents);
}); };
/**
 * Function to inline styles into their respective file & space.
 * @param fileKey - a base/name.liquid string or null to glob all liquid files for testing.
 */
const linkStyles = (fileKey) => __awaiter(void 0, void 0, void 0, function* () {
    var e_2, _a;
    const liquidFiles = (fileKey !== null)
        ? [fileKey]
        : yield (0, fast_glob_1.default)([`${_directorys_1.default.productionRoot}/**/*.liquid`]);
    const linkRegex = /<!--mango-link:(.*?)-->/gm;
    try {
        for (var liquidFiles_1 = __asyncValues(liquidFiles), liquidFiles_1_1; liquidFiles_1_1 = yield liquidFiles_1.next(), !liquidFiles_1_1.done;) {
            const liquidFile = liquidFiles_1_1.value;
            const fileBuffer = yield fs_extra_1.default.readFile(liquidFile);
            const fileContents = fileBuffer.toString();
            const fileContentsMatch = fileContents.match(linkRegex);
            if (fileContentsMatch)
                yield insertStyleSheet(liquidFile, fileContents, fileContentsMatch);
        }
    }
    catch (e_2_1) { e_2 = { error: e_2_1 }; }
    finally {
        try {
            if (liquidFiles_1_1 && !liquidFiles_1_1.done && (_a = liquidFiles_1.return)) yield _a.call(liquidFiles_1);
        }
        finally { if (e_2) throw e_2.error; }
    }
});
exports.default = linkStyles;
