/*  OpenTally: Open-source election vote counting
 *  Copyright © 2021 Lee Yingtong Li (RunasSudo)
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

function clickAdvancedOptions() {
	if (document.getElementById('divAdvancedOptions').style.display === 'none') {
		document.getElementById('divAdvancedOptions').style.display = 'grid';
		document.getElementById('btnAdvancedOptions').innerHTML = 'Hide advanced options';
	} else {
		document.getElementById('divAdvancedOptions').style.display = 'none';
		document.getElementById('btnAdvancedOptions').innerHTML = 'Show advanced options';
	}
}

var tblResult = document.getElementById('result');
var divLogs2 = document.getElementById('resultLogs2');
var olStageComments;

var worker = new Worker('worker.js');

worker.onmessage = function(evt) {
	if (evt.data.type === 'init') {
		document.getElementById('spanRevNum').innerText = evt.data.version;
		document.getElementById('divLoading').style.display = 'none';
		document.getElementById('divUI').style.display = 'block';
		
	} else if (evt.data.type === 'initResultsTable') {
		tblResult.innerHTML = evt.data.content;
		divLogs2.innerHTML = '<p>Stage comments:</p>';
		olStageComments = document.createElement('ol');
		divLogs2.append(olStageComments);
		
	} else if (evt.data.type === 'describeCount') {
		document.getElementById('resultLogs1').innerHTML = evt.data.content;
		
	} else if (evt.data.type === 'updateResultsTable') {
		for (let i = 0; i < evt.data.result.length; i++) {
			if (evt.data.result[i]) {
				tblResult.rows[i].insertAdjacentHTML('beforeend', evt.data.result[i]);
				
				// Update candidate status
				if (i >= 3 && i % 2 == 1) {
					if (tblResult.rows[i].lastElementChild.classList.contains('elected')) {
						tblResult.rows[i].cells[0].classList.add('elected');
					} else {
						tblResult.rows[i].cells[0].classList.remove('elected');
					}
				}
			}
		}
		
	} else if (evt.data.type === 'updateStageComments') {
		let elLi = document.createElement('li');
		elLi.innerHTML = evt.data.comment;
		olStageComments.append(elLi);
		
	} else if (evt.data.type === 'finalResultSummary') {
		divLogs2.insertAdjacentHTML('beforeend', evt.data.summary);
	}
}

worker.onerror = function(evt) {
	alert('An unknown error occurred while counting the votes. More details may be available in the browser\'s developer console.');
}

async function clickCount() {
	if (document.getElementById('bltFile').files.length === 0) {
		return;
	}
	
	// Read BLT file
	let filePath = document.getElementById('bltFile').value;
	filePath = filePath.substring(Math.max(filePath.lastIndexOf('\\'), filePath.lastIndexOf('/')) + 1);
	
	let bltFile = document.getElementById('bltFile').files[0];
	let electionData = await bltFile.text();
	
	// Init STV options
	let optsStr = [
		document.getElementById('chkRoundTVs').checked ? parseInt(document.getElementById('txtRoundTVs').value) : null,
		document.getElementById('chkRoundWeights').checked ? parseInt(document.getElementById('txtRoundWeights').value) : null,
		document.getElementById('chkRoundVotes').checked ? parseInt(document.getElementById('txtRoundVotes').value) : null,
		document.getElementById('chkRoundQuota').checked ? parseInt(document.getElementById('txtRoundQuota').value) : null,
		document.getElementById('selQuota').value,
		document.getElementById('selQuotaCriterion').value,
		document.getElementById('selTransfers').value,
		document.getElementById('selSurplus').value,
		document.getElementById('selPapers').value == 'transferable',
		document.getElementById('selExclusion').value,
		parseInt(document.getElementById('txtPPDP').value),
	];
	
	// Dispatch to worker
	worker.postMessage({
		'type': 'countElection',
		'electionData': electionData,
		'optsStr': optsStr,
		'filePath': filePath,
		'numbers': document.getElementById('selNumbers').value,
		'decimals': document.getElementById('txtDP').value,
	});
}

// Presets

function changePreset() {
	if (document.getElementById('selPreset').value === 'scottish') {
		document.getElementById('selQuotaCriterion').value = 'geq';
		document.getElementById('selQuota').value = 'droop';
		//document.getElementById('selQuotaMode').value = 'static';
		//document.getElementById('chkBulkElection').checked = true;
		//document.getElementById('chkBulkExclusion').checked = false;
		//document.getElementById('chkDeferSurpluses').checked = false;
		document.getElementById('selNumbers').value = 'fixed';
		document.getElementById('txtDP').value = '5';
		document.getElementById('txtPPDP').value = '2';
		document.getElementById('chkRoundQuota').checked = true;
		document.getElementById('txtRoundQuota').value = '0';
		document.getElementById('chkRoundVotes').checked = false;
		document.getElementById('chkRoundTVs').checked = false;
		document.getElementById('chkRoundWeights').checked = false;
		document.getElementById('selSurplus').value = 'by_size';
		document.getElementById('selTransfers').value = 'wig';
		document.getElementById('selPapers').value = 'both';
		document.getElementById('selExclusion').value = 'single_stage';
		//document.getElementById('selTies').value = 'backwards_random';
	} else if (document.getElementById('selPreset').value === 'senate') {
		document.getElementById('selQuotaCriterion').value = 'geq';
		document.getElementById('selQuota').value = 'droop';
		//document.getElementById('selQuotaMode').value = 'static';
		//document.getElementById('chkBulkElection').checked = true;
		//document.getElementById('chkBulkExclusion').checked = true;
		//document.getElementById('chkDeferSurpluses').checked = false;
		document.getElementById('selNumbers').value = 'fixed';
		document.getElementById('txtDP').value = '5';
		document.getElementById('txtPPDP').value = '0';
		document.getElementById('chkRoundQuota').checked = true;
		document.getElementById('txtRoundQuota').value = '0';
		document.getElementById('chkRoundVotes').checked = true;
		document.getElementById('txtRoundVotes').value = '0';
		document.getElementById('chkRoundTVs').checked = false;
		document.getElementById('chkRoundWeights').checked = false;
		document.getElementById('selSurplus').value = 'by_order';
		document.getElementById('selTransfers').value = 'uig';
		document.getElementById('selPapers').value = 'both';
		document.getElementById('selExclusion').value = 'by_value';
		//document.getElementById('selTies').value = 'backwards_random';
	} else if (document.getElementById('selPreset').value === 'prsa77') {
		document.getElementById('selQuotaCriterion').value = 'geq';
		document.getElementById('selQuota').value = 'droop';
		//document.getElementById('selQuotaMode').value = 'static';
		//document.getElementById('chkBulkElection').checked = true;
		//document.getElementById('chkBulkExclusion').checked = false;
		//document.getElementById('chkDeferSurpluses').checked = true;
		document.getElementById('selNumbers').value = 'fixed';
		document.getElementById('txtDP').value = '5';
		document.getElementById('txtPPDP').value = '3';
		document.getElementById('chkRoundQuota').checked = true;
		document.getElementById('txtRoundQuota').value = '3';
		document.getElementById('chkRoundVotes').checked = true;
		document.getElementById('txtRoundVotes').value = '3';
		document.getElementById('chkRoundTVs').checked = true;
		document.getElementById('txtRoundTVs').value = '3';
		document.getElementById('chkRoundWeights').checked = true;
		document.getElementById('txtRoundWeights').value = '3';
		document.getElementById('selSurplus').value = 'by_order';
		document.getElementById('selTransfers').value = 'eg';
		document.getElementById('selPapers').value = 'transferable';
		document.getElementById('selExclusion').value = 'parcels_by_order';
		//document.getElementById('selTies').value = 'backwards_random';
	}
}
