const path = require('path');
const fs = require('fs');

const config = require('../config/lang');
const srcPath = path.join(__dirname,"..","src");
const langPath = path.join(srcPath,"lang");
const componentPath = path.join(srcPath,"lang","component");
let allFilePath = [];
function getAllLang(...dirs){
	let langGroup = {};
	for(let dir of dirs){
		if(fs.existsSync(dir)){
			for(let lang of config.lang){
				let lPath = path.join(dir,"/",`${lang}.json`);
				if(fs.existsSync(lPath)){
					let arr;
					if(langGroup[lang]!=null){
						arr = langGroup[lang];
					}else{
						arr = new Array();
					}
					arr.push(lPath);
					langGroup[lang] = arr;
					allFilePath.push(lPath);
				}
			}
		}	
	}
	return langGroup;
}
let langGroup;
const watch = require('watch');
class I18NPackage{
	constructor(options){
		this.options = options;
		this.watching = false;
	}

	apply(compiler){
		langGroup = getAllLang(langPath,componentPath);
		compiler.plugin("watch-run", (compilation, callback) => {
			if(!this.watching){
				this.watching = true;
				langGroup = getAllLang(langPath,componentPath);
				const onChange = () => {
					langGroup = getAllLang(langPath,componentPath);
					compiler.run((err) => {
						if(err) {
						  throw err;
						}
					});
				};
				watch.createMonitor(srcPath, (monitor) => {
					monitor.files[path.join(srcPath,".json")];

					monitor.on("created", onChange);
					monitor.on("changed", onChange);
					monitor.on("removed", onChange);
					callback();
				});
			}
			
		});
		compiler.plugin('emit', function(compilation, callback) {
			let createFileName = [];
			try{
				for(let key of Object.keys(langGroup)){
					let path = langGroup[key];
					let obj = {};
					for(let filePath of path){
						obj = Object.assign(obj,JSON.parse(fs.readFileSync(filePath, 'utf8')));
					}
					let filelist = JSON.stringify(obj);
					// Insert this list into the Webpack build as a new file asset:
					let fileName = `../resources/lang/${key}.json`;
					compilation.assets[fileName] = {
						source: function() {
							return filelist;
						},
						size: function() {
							return filelist.length;
						}
					};
					createFileName.push(fileName);
				}
			}catch(err){
				console.log(err)
			}
			console.log("lang file merge success.")
			for(let file of createFileName){
				console.log(file)
			}

			callback();
		});
	}
}
module.exports = I18NPackage;