"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = transpileStyled;
const tslib_1 = require("tslib");
const glob_1 = require("glob");
const FilePath_1 = require("./FilePath");
const promises_1 = require("fs/promises");
const SourceMapReMap_1 = require("./SourceMapReMap");
function transpileStyled(_a) {
    return tslib_1.__awaiter(this, arguments, void 0, function* ({ sourceFile, targets, result, rule, AtRule }) {
        var _b, e_1, _c, _d;
        var _e;
        const sourceFilePath = new FilePath_1.default(sourceFile);
        try {
            for (var _f = true, _g = tslib_1.__asyncValues((0, glob_1.globIterate)(targets, {
                absolute: true,
                cwd: sourceFilePath.dir
            })), _h; _h = yield _g.next(), _b = _h.done, !_b; _f = true) {
                _d = _h.value;
                _f = false;
                const file = _d;
                const nodeFilePath = new FilePath_1.default(file);
                console.log(`Compiling ${nodeFilePath.filePath}`);
                let r = require(nodeFilePath.filePath);
                r = (_e = r === null || r === void 0 ? void 0 : r.default) !== null && _e !== void 0 ? _e : r;
                const fileResult = r;
                if (!fileResult) {
                    result.warn(`JavaScript file did not return Style object`, {
                        node: rule
                    });
                    continue;
                }
                const fp = new FilePath_1.default(nodeFilePath.dir);
                const sourceRoot = fp.webPath;
                const cssFilePath = nodeFilePath.filePath.replace(".css.js", ".css");
                const csp = new FilePath_1.default(cssFilePath);
                const { code: source, map: sourceMap } = fileResult.toStringWithSourceMap({});
                yield (0, promises_1.writeFile)(cssFilePath, `${source}\n/*# sourceMappingURL=${csp.name}.map */`, "utf-8");
                yield (0, promises_1.writeFile)(cssFilePath + ".map", SourceMapReMap_1.default.save(sourceMap, sourceRoot), "utf-8");
                const relativePath = new FilePath_1.default(cssFilePath)
                    .relativeTo(new FilePath_1.default(rule.source.input.file));
                const replacedRule = new AtRule({
                    name: 'import',
                    params: `"${relativePath}"`,
                    source: rule.source,
                });
                rule.before(replacedRule);
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (!_f && !_b && (_c = _g.return)) yield _c.call(_g);
            }
            finally { if (e_1) throw e_1.error; }
        }
    });
}
//# sourceMappingURL=transpileStyled.js.map