/* deplacer le build vers le dossier src/static */
const fs = require('fs')
const path = require('path')
const ncp = require('ncp').ncp
ncp.limit = 16;
const rimraf = require('rimraf')

const srcJsPath = path.dirname(__dirname)
const iconolabSrcPath = path.join(srcJsPath,"..","src")
const destJsDir = path.join(iconolabSrcPath, "iconolab", "static","iconolab", "js")
const destCssDir = path.join(iconolabSrcPath,"iconolab", "static","iconolab", "css")



var copyFile = function (src, dest, callback) {
	try {
		
		fs.accessSync(src, fs.R_OK);
		fs.accessSync(path.dirname(dest), fs.W_OK);
		
		// handler error
		var errorHandler = function (e) {
			callback(e);
		}

		var readStream = fs.createReadStream(src);

		var writeStream = fs.createWriteStream(dest);

		readStream.on("error", errorHandler);
		writeStream.on("error", errorHandler);

		readStream.on("data", function (chunk) {
			writeStream.write(chunk);			
		});

		readStream.on("end", function () {
			writeStream.close();
		});

	} catch (e) {
		console.log(e);
		if(typeof callback === "function") {
			callback(e);
		}
	}
}

//move js
copyFile(
	path.join(srcJsPath, "iconolab-bundle", "dist", "iconolab.js"), 
	path.join(destJsDir, "iconolab.js")
	)


const bootstrapPath = path.join(srcJsPath, "iconolab-bundle", "node_modules", "bootstrap");
const fontAwesomeCssPath = path.join(srcJsPath, "iconolab-bundle", "node_modules", "font-awesome","css","font-awesome.min.css");
const fontAwesomeDir = path.join(srcJsPath, "iconolab-bundle", "node_modules", "font-awesome");

//copyFile(bootstrapPath, path.join(destCssDir, "bootstrap.min.css"));



/* boostrap: we copy the dist folder*/
rimraf(path.join(destCssDir, 'bootstrap'), function () {
	 ncp(path.join(bootstrapPath, "dist"), path.join(destCssDir, "bootstrap"), function (e) {
	 	if (e) {
	 		console.log(e);
	 		console.log("Erreur pendant la copie de boostrap vers le dossier dist");
	 	}
	 });
});


/* delete font-awesome folder */
rimraf(path.join(destCssDir,'font-awesome'), function (e) {
		fs.access(path.join(destCssDir,'font-awesome'), fs.F_OK, function (hasError) {
			if (hasError) {
				fs.mkdir(path.join(destCssDir,'font-awesome'), function (hasError) {
					if (!hasError) {
						fs.mkdir(path.join(destCssDir,'font-awesome','css'), function (hasError) {
							if (!hasError) {
								copyFile(fontAwesomeCssPath, path.join(destCssDir, "font-awesome", "css", "font-awesome.min.css"));
								ncp(path.join(fontAwesomeDir, "fonts"), path.join(destCssDir, "font-awesome", "fonts"));
							}
						})
						
					} else {
						console.log(e);
					}
				});
			} 
		});
});



