const { app, BrowserWindow, ipcMain } = require('electron')
const Store = require('electron-store')
const path = require('path')
const store = new Store()
const Alert = require("electron-alert");

	var objState = [
        {id: 0, state: ''},
        {id: 1, state: ''},
        {id: 2, state: ''},
        {id: 3, state: ''},
        {id: 4, state: ''},
        {id: 5, state: ''},
        {id: 6, state: ''}
    ]
	
app.whenReady().then(() => {
    const win = new BrowserWindow({
        width: 800,
        height: 500,
		resizable: false,
        icon: __dirname + '/icon.ico',
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: true,
            contextIsolation: false,
            devTools: true
        }
    })

    win.setMenuBarVisibility(false)

    win.loadFile('src/index.html')

    const { spawn } = require('child_process')

    const ps = spawn(path.join(__dirname, 'binaries\\receivemidi.exe'), ['dev', 'MIDI function', 'cc'])

    console.log("RP2T started...")

    let obj = [
        {id: 0, level: 0},
        {id: 1, level: 0},
        {id: 2, level: 0},
        {id: 3, level: 0},
        {id: 4, level: 0},
        {id: 5, level: 0},
        {id: 6, level: 0}
    ]
	


    ps.stdout.on('data', (data) => {
        const data_string = data.toString().replace(/\s/g, '');
		
		let array_from_filtered_string = data_string.split('channel');
		array_from_filtered_string = array_from_filtered_string.filter(function(e){return e}); 
		array_from_filtered_string = array_from_filtered_string.map(i => 'channel' + i);
		

		array_from_filtered_string.forEach((element) => {
		  
		          if(element.startsWith("channel") && element.includes("-change15")) {
						const channel_number = parseInt(element.split('channel').pop().split('control')[0])

						let channel_level = parseInt(element.split('-change15')[1]);
						
						obj[channel_number].level = channel_level;
						
						batchProcesses(channel_number, channel_level);
						
						const json = JSON.stringify(obj)
						win.webContents.send('data-communication', json);
				   }
		
		});
		

    })

    ps.stderr.on('data', (data) => {
        console.log("Error")
        console.log(data)
    })
	
	ipcMain.on('resize-half', (event) => {
		let browserWindow = BrowserWindow.fromWebContents(event.sender)
		browserWindow.setMinimumSize(800,500)
		browserWindow.setSize(800,500)
	})
	
	ipcMain.on('resize-full', (event) => {
		let browserWindow = BrowserWindow.fromWebContents(event.sender)
		browserWindow.setMinimumSize(800,950)
		browserWindow.setSize(800,950)
	})
	
	ipcMain.on('save-to-config', (event, configKey, configValue) => {
		store.set(configKey, configValue);
	})
	
	ipcMain.on('get-value-and-send-back', (event, configKey) => {
		let valueFromConfig = store.get(configKey);
		let getKeyForm = 'getkey-' + configKey;
		win.webContents.send(getKeyForm, valueFromConfig);
	})
	
	ipcMain.on('toast', (event, message) => {
		let alert = new Alert();

		let dialogOptions = {
			text: message,
			icon: "success",
			color: '#fff',
			background: '#000',
			showCancelButton: false
		};

		alert.fireFrameless(dialogOptions);
	})
	

 
    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
})

function batchProcesses(channel, level) {
  if(level >= 1) {
	if(objState[channel].state != 'on') {
		objState[channel].state = 'on';	
		runBatch(channel, 'on');
		runWemo(channel, 'on');
	}
  } else {
	if(objState[channel].state != 'off') {
		objState[channel].state = 'off';	
		runBatch(channel, 'off');
		runWemo(channel, 'off');
	}
  }
}

function runBatch(channel, mode) {
	try {
		const { spawn } = require('child_process')
		script_path = store.get('script-' + mode + '-channel-' + channel);
		
		if(script_path == "") { script_path = undefined; }
		
		if(script_path != null){			
			let ps2 = spawn(script_path, []);
			
			ps2.on('error', function(error) {
				let alert = new Alert();

				let dialogOptions = {
					text: 'An error occured: ' + error,
					icon: "error",
					color: '#fff',
					background: '#000',
					showCancelButton: false
				};

				alert.fireFrameless(dialogOptions);
			});
		}	
	} catch (error) {
		let alert = new Alert();

		let dialogOptions = {
			text: 'An error occured: ' + error,
			icon: "error",
			color: '#fff',
			background: '#000',
			showCancelButton: false
		};

		alert.fireFrameless(dialogOptions);
	}
}


function runWemo(channel, mode) {	
    let modeN;
	
	try {
		wemo_ip = store.get('wemo-device-ip-channel-' + channel);
		
		if(wemo_ip == "") { wemo_ip = undefined; }
		
		if(wemo_ip != null){	
		
		   if(mode == "off") { modeN = "0"; }
		   if(mode == "on") { modeN = "1"; }

       	    var dataW = '<?xml version="1.0" encoding="utf-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body><u:SetBinaryState xmlns:u="urn:Belkin:service:basicevent:1"> <BinaryState>' + modeN + '</BinaryState></u:SetBinaryState></s:Body></s:Envelope>';
			
			const p = require('phin').unpromisified;

			p({
				url: 'http://' + wemo_ip.trim() + ':49153/upnp/control/basicevent1',
				method: 'POST',
				data: dataW,
				headers: {
					'Content-Type': 'text/xml; charset=utf-8',
					'SOAPACTION': '"urn:Belkin:service:basicevent:1#SetBinaryState"'
				}
			})
			
			console.log(p.body);

		}	
	} catch (error) {
		let alert = new Alert();

		let dialogOptions = {
			text: 'An error occured: ' + error,
			icon: "error",
			color: '#fff',
			background: '#000',
			showCancelButton: false
		};

		alert.fireFrameless(dialogOptions);
	}
}