"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 fs_extra_1 = __importDefault(require("fs-extra"));
const _directorys_1 = __importDefault(require("../utils/_directorys"));
const _fsUtils_1 = require("../utils/_fsUtils");
const auditSnippets = (spinner) => __awaiter(void 0, void 0, void 0, function* () {
    var e_1, _a;
    const { snippetsRoot } = _directorys_1.default;
    spinner.stopAndPersist({
        symbol: '✂️',
        text: `Reading snippets from ${snippetsRoot}`,
    });
    // get all the snippet files
    const snippetFiles = yield fs_extra_1.default.readdir(snippetsRoot);
    // initialize an array of all the snippets without the .liquid ext.
    const allSnippets = snippetFiles.map((snippet) => snippet && snippet.replace('.liquid', '')).filter(Boolean);
    // read all of the working theme directorys
    const files = [...yield (0, _fsUtils_1.auditDirectoryFiles)()];
    // initialize an array for regexp matches
    const snippetMatches = [];
    // initialize an array of regexpressions to match.
    // `(\\{\\%|\\s|)(|\\-)((|\\s)(render|include)(|\\s)(\\'|\\")${snippet.replace('.liquid', '')})`
    // matches any render or include statement even inside a capture or liquid expression.
    const snippetRegexp = snippetFiles.map((snippet) => snippet && new RegExp(`(\\{\\%|\\s|)(|\\-)((|\\s)(render|include)(|\\s)(\\'|\\")${snippet.replace('.liquid', '')})`, 'g'));
    try {
        // loop through liquid files and push the results from the match to our snippetsMatch array.
        for (var files_1 = __asyncValues(files), files_1_1; files_1_1 = yield files_1.next(), !files_1_1.done;) {
            const file = files_1_1.value;
            if (file.includes('.liquid')) {
                spinner.stopAndPersist({
                    symbol: '✂️',
                    text: `Auditing ${file}`,
                });
                const fileBuffer = yield fs_extra_1.default.readFile(file);
                const fileContent = fileBuffer.toString();
                snippetRegexp.forEach((regexp) => snippetMatches.push(fileContent.match(regexp)));
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (files_1_1 && !files_1_1.done && (_a = files_1.return)) yield _a.call(files_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    // initialize a new array with no duplicates of all snippets in use for comparison.
    const snippetsInUse = [
        ...new Set(snippetMatches.flat()
            .filter(Boolean)
            .map((snippet) => snippet.replace(/(\{%|\s|)(|-)((|\s)(render|include)(\s|)('|"))/g, '')
            .replace(/(',|",|'\s|"\s)(.*?)\}/g, '')
            .replace(/'/g, '')
            .trim())),
    ];
    const notInUse = allSnippets.map((snippet) => !snippetsInUse.includes(snippet) && snippet).filter(Boolean);
    // returns the snippets not found to be inuse from comparing with our snippetsInUse array. 
    return notInUse;
});
exports.default = auditSnippets;
