'use strict';

var path = require('path');
var fs = require('fs');
var ignoreExt = ['.meta','.pac']; //忽略文件类型
var json_file_url = "db://assets/EventJSON/" // 事件配置所在文件夹
var out_file = "db://assets/Scripts/utils/EventsID.js"
var out_content = "";
//扫描文件
function scanResFiles(dir) {
    let files = fs.readdirSync(dir);
    
    for (let i = 0; i < files.length; i++) {
        let file = files[i];
        let file_path = path.join(dir, file);
        let stat = fs.lstatSync(file_path);
        
        if (stat.isDirectory()) {
            scanResFiles(file_path);           
        } else {
            if (!isIgnore(file_path)) {
             // let ext = path.extname(file_path).toLocaleLowerCase();
             let filebasename = path.basename(file_path);
             filebasename = filebasename.split('.')[0];
             
             var script = fs.readFileSync(file_path, 'utf8');     // 读取构建好的 js
             out_content += `lg.${filebasename} = ${script};\n`;
            }
        }
    }
}

function genEventsJS(){
      //扫描所有文件夹
      let fspath = Editor.assetdb.urlToFspath(json_file_url);
      scanResFiles(fspath);
      Editor.log('export: '+out_content);
      
      let out_file_path = Editor.assetdb.urlToFspath(out_file);
      
    //   var script = fs.readFileSync(out_file_path, 'utf8');     // 读取构建好的 js
    //   script = out_content;
      fs.writeFileSync(out_file_path, out_content,{
        flag: 'w'
      });

    //   if (Editor.assetdb.exists(out_file)) {
    //     Editor.assetdb.saveExists(out_file, out_content, function (err, meta) {
    //         Editor.success("R.ts generate finished!");
    //     });
    // } else {
    //     Editor.assetdb.create(out_file, out_content, function (err, meta) {
    //         Editor.success("R.ts generate finished!");
    //     });
    // }
}


function isIgnore(fileName) {
    let ext = path.extname(fileName).toLocaleLowerCase();
    for (let i = 0; i < ignoreExt.length; i++) {
        const element = ignoreExt[i];
        if(element == ext){
            return true;
        }
    }
    return false;
}

module.exports = {
  load () {
    // execute when package loaded
  },

  unload () {
    // execute when package unloaded
  },

  // register your ipc messages here
  messages: {
    'export' () {
      // open entry panel registered in package.json
      Editor.log('export');
      out_content = "";
      genEventsJS()
    },
  },
};