import { passthrough } from 'p-transform';
import { isFileStateModified } from 'mem-fs-editor/state';
import prettier from 'prettier';
import prettierPluginJava from 'prettier-plugin-java';
import prettierPluginProperties from 'prettier-plugin-properties';
import prettierPluginPackagejson from 'prettier-plugin-packagejson';
import { Minimatch } from 'minimatch';
const minimatch = new Minimatch('**/{.prettierrc**,.prettierignore}');
export const isPrettierConfigFilePath = (filePath) => minimatch.match(filePath);
export const isPrettierConfigFile = (file) => isPrettierConfigFilePath(file.path);
export const createPrettierTransform = async function (options = {}) {
    await prettier.clearConfigCache();
    const { ignoreErrors = false, extensions = '*', prettierPackageJson, prettierJava, prettierProperties, prettierOptions } = options;
    const globExpression = extensions.includes(',') ? `**/*.{${extensions}}` : `**/*.${extensions}`;
    const minimatch = new Minimatch(globExpression, { dot: true });
    return passthrough(async (file) => {
        if (!minimatch.match(file.path) || !isFileStateModified(file)) {
            return;
        }
        if (!file.contents) {
            throw new Error(`File content doesn't exist for ${file.relative}`);
        }
        let fileContent;
        try {
            if (file.relative.includes('/uni_modules/') || file.relative.includes('.min.js') || file.relative.includes('assets/vendor/') || file.relative.includes('.min.css') || file.relative.includes('assets/vendor/')) {
                return;
            }
            const resolvedDestinationFileOptions = await prettier.resolveConfig(file.relative);
            const fileOptions = {
                ...resolvedDestinationFileOptions,
                plugins: [],
                filepath: file.relative,
                ...prettierOptions,
            };
            if (prettierPackageJson && file.path.endsWith('package.json')) {
                fileOptions.plugins.push(prettierPluginPackagejson);
            }
            if (prettierJava && file.path.endsWith('.java')) {
                fileOptions.plugins.push(prettierPluginJava);
            }
            if (prettierProperties) {
                fileOptions.plugins.push(prettierPluginProperties);
            }
            fileContent = file.contents.toString('utf8');
            const data = await prettier.format(fileContent, fileOptions);
            file.contents = Buffer.from(data);
        }
        catch (error) {
            let errorMessage;
            if (fileContent) {
                errorMessage = `Error parsing file ${file.relative}: ${error}

At: ${fileContent
                    .split('\n')
                    .map((value, idx) => `${idx + 1}: ${value}`)
                    .join('\n')}`;
            }
            else {
                errorMessage = `Unknown prettier error: ${error}`;
            }
            if (ignoreErrors) {
                this?.log?.warn?.(errorMessage);
                return;
            }
            throw new Error(errorMessage);
        }
    });
};
