//@ts-nocheck
import  fs from "fs";
import postcss from "postcss";
import atImport from "postcss-import";
import path from 'path';
import less from 'less';

const syntax = require('postcss-less');



const command = `less [entryPath]`;
const aliases = ['less','-l'];
const desc = 'Less打包命令';
const builder = (yargs:any) => {

};

const handler = async function (argv:any) {
    const {
        entryPath,
        cssName
    } = argv;
    console.log('开始Less打包！');
    less.render(fs.readFileSync(path.join(process.cwd(), entryPath),{encoding:'utf-8'}), {
        filename: path.resolve(entryPath),
    },function (e, output) {
        console.log(output);
        postcss([]).use(atImport())
            .process(output.css, {
                syntax: syntax ,
                from: path.join(process.cwd(), entryPath)
            })
            .then(function (result) {
                console.log(result);
                createDirectory('dist');
                fs.writeFileSync('./dist/'+ 'theme' +'.css',result.css);
            })
    })
};

function createDirectory(str){
    const path = [];
    const arr = str.split("/");
    const len = arr.length;
    arr.map((v:any,i)=>{
        path.push(v);
        const filename = path.join("/");
        // 判断这个文件或文件夹是否存在
        const bln = fs.existsSync(filename);
        if( bln == false ){
            if( i<len-1 ){  // 一定是文件夹
                console.log( "创建 "+filename+" 文件夹" );
                fs.mkdirSync(filename);
            }else{
                // 判断是文件还是文件夹
                if( arr[i].indexOf(".") > -1 ){
                    // 如果是文件
                    console.log( "创建文件"+filename );
                }else{
                    // 如果是文件夹
                    console.log( "创建文件夹"+filename );
                    fs.mkdirSync(filename);
                }
            }
        }
    })
}



export default {
    command,
    desc,
    builder,
    handler,
    aliases
}


