const fs = require('fs');
const path = require('path');
// const pathThreeAdapterEntry = require.resolve('./index');
const cp = require('child_process');

const adapterPath = path.resolve(__dirname, './', 'threejs-adapter');
const adapterFilePath = path.resolve(adapterPath, 'dist', 'index.js');

module.exports = function resolveThreeModule() {
    console.log('\n\n[bili-info]：检测到用户使用three，请确保使用three版本为 version=0.133.0');
    const callback = this.async();
    console.log('\n[bili-info]：初始化three adapter...');

    fs.access(adapterFilePath, fs.F_OK, (err) => {
        if (err) {
            console.log('\n[bili-info]：本地无缓存编译three adapter，编译中...\n');
            cp.exec(`cd ${adapterPath} && npm install && CWD=${process.cwd()} npm run build`, {}, (err, stdout) => {
                // console.log(err,stdout)
                console.log('\n\n[bili-info]：编译three adapter成功。\n');

                const code = fs.readFileSync(adapterFilePath, 'utf-8');
                callback(err, code);
                console.log('[bili-info]：编译完成 - three adapter\n');
            });
            return;
        }
        console.log('\n[bili-info]：命中编译缓存 - three adapter\n');
        const code = fs.readFileSync(adapterFilePath, 'utf-8');
        callback(err, code);
        console.log('[bili-info]：编译完成。\n');
    });
};
