import { XwebConfig } from "../config/config.js";
import { XwebIgnores } from "../config/ignore.js";

import path from "path";
import fs from "fs";
import { info, status } from "../log.js";

function has_file_extension(file_name: string, extension_to_check: string): boolean {
    return file_name.endsWith(extension_to_check);
}

function should_ignore(name: string, IGNORE_LIST: string[]): boolean {
    for (const IGNORE of IGNORE_LIST) {
        if (name.endsWith(IGNORE)) return true;
    }
    return false;
}

function scan_folder(root_folder: string, current_child_folder: string, CONFIG: XwebConfig, IGNORES: XwebIgnores): string[] {
    const FILES_FOUND: string[] = [];
    const FOLDER_CONTENT = fs.readdirSync(path.join(root_folder, current_child_folder), { withFileTypes: true });
    FOLDER_CONTENT.forEach(folder_item => {
        if (
            folder_item.isFile() &&
            has_file_extension(folder_item.name, CONFIG.extension.src) &&
            !should_ignore(folder_item.name, IGNORES.files)
        ) {
            info("run/scan", `Found file '${path.join(current_child_folder, folder_item.name)}'`);
            FILES_FOUND.push(path.join(current_child_folder, folder_item.name));
        } else if (
            folder_item.isDirectory() &&
            !should_ignore(folder_item.name, IGNORES.directories)
        ) {
            status("run/scan", `Scanning folder '${path.join(current_child_folder, folder_item.name)}'`);
            FILES_FOUND.push(
                ...scan_folder(root_folder, path.join(current_child_folder, folder_item.name), CONFIG, IGNORES)
            );
        }
    });
    return FILES_FOUND;
}

export function scan_for_files(CONFIG: XwebConfig, IGNORES: XwebIgnores): string[] {
    info("run/scan", `Scanning for ${CONFIG.extension.src} files in the '${CONFIG.folder.src}' folder`);
    return scan_folder(path.join(process.cwd(), CONFIG.folder.src), "", CONFIG, IGNORES);
}