// This file contains function that are Electron/Node.JS specific

// Load required packages
const Plotly = require('plotly.js-dist');
const ipcRenderer = require('electron').ipcRenderer;
const fs = require('fs');
const exec = require('child_process').execSync;
const remote = require('electron').remote;

function getFiles(dir, filelist){
    fileList = [];
    var files = fs.readdirSync(dir);
    for(var i of files){
        if (!files.hasOwnProperty(i)) continue;
        var name = dir+'/'+files[i];
        if (!fs.statSync(name).isDirectory()){
            fileList.push(name);
        }
    }
    return fileList;
}

function execute(command) {
    exec(command, {stdio: 'inherit'});
}

function checkDir(directory) {
    // Check whether directory exists, if not create it
    if (!fs.existsSync(directory)) {
	// Folder does not exist try to create it
	fs.mkdir(directory,{recursive: true}, (err) => {
	    if (err) {
		alert('Cannot create data folder '+directory);
		return(0);
	    }
	});
    }
    return(1);
}

function writeAsciiFile(filename,content) {
    // Write string content into ascii file filename
    try { fs.writeFileSync(filename, content, 'utf-8'); }
    catch(e) {
	alert('Failed to save '+filename);
	return(0);
    }
    return(1);
}

function readAsciiFile(filename) {
    // Read ascii file filename and return content in a string
    var content;
    // If an array of filenames was sent take the first one only
    if (Array.isArray(filename)) {filename=filename[0];}
    try {
	content = fs.readFileSync(filename, 'utf8');
    } catch(e) {
	alert('Failed to read '+filename);
	return(0);
    }
    return(content);
}
	       
function fileExists(filename) {
    try {
	if (fs.existsSync(filename)) {
	    return 1;
	}
    }catch(err) {
	console.log(err);
    }
    return 0;
}

function firstLoad() {
    document.getElementById("trimPath").value = remote.getGlobal('path');
    
    // Catch calls for open file
    ipcRenderer.on('openFile', function(event, filename) {
	console.log('Open file '+filename);
	fs.readFile(filename.toString(), function read(err, data) {
	    if (err) {
		throw err;
	    }
	    setValues(data);
	});
    });
    
    // Catch calls for selectfolder
    ipcRenderer.on('selectFolder', function(event, foldername) {
	if (foldername.length != 0) {
	    document.getElementById("workPath").value = foldername[0];
	    // Change process directory
	    process.chdir(foldername[0]);
	}
	console.log("currentdir",process.cwd());
    });
    // Catch calls for save as
    ipcRenderer.on('saveFile', function(event, filename) {
	// If filename is empty use default value
	if (filename == '') {filename='TrimSP.cfg';}
	// Get values from all fields and prepare config file
	let trimSPcfg=prep_cfg(0);
	// Save file to filename
	console.log('Save file to '+filename);
	try { fs.writeFileSync(filename, trimSPcfg, 'utf-8'); }
	catch(e) { alert('Failed to save the file !'); }
    });
    // Catch calls for plotProf
    ipcRenderer.on('plotProf', function(event, filename) {
	console.log("filename="+filename);
	plotProfiles(filename);
    });
    // Catch calls for plotFrac
    ipcRenderer.on('plotFrac', function(event, filename) {
	console.log("filename="+filename);
	plotFractions(filename);
    });
    // Catch calls for plotMean
    ipcRenderer.on('plotMean', function(event, filename) {
	console.log("filename="+filename);
	plotMean(filename);
    });
    // Catch clicks for Browse button
    ipcRenderer.on('browseFolder', function(event, foldername) {
	if (foldername.length != 0) {
	    document.getElementById("workPath").value = foldername[0];
	    // Change process directory
	    process.chdir(foldername[0]);
	}
    });
}
