/*
Function: Used to return Params: Chain_ID, Account_Creation_Fee, and Maximum_Block_Size
*/
function GetChainData(callback) {
	console.log("Function: GetChainData()".green.bold);


    wls.api.getChainProperties(function(err, result) {
      account_creation_fee = result.account_creation_fee;
      maximum_block_size = result.maximum_block_size;
			// console.log("Logging type of maximum_block_size: ".blue.bold, typeof maximum_block_size);
			console.log("Creation Fee: ".gray.bold, account_creation_fee.magenta.bold);
			console.log("Max Block Size: ".gray.bold, maximum_block_size.toString().magenta.bold);

    });

    wls.api.getConfig(function(err, result) {
			// console.log(result);
      chain_id = result.WLS_CHAIN_ID;
			if (chain_id === undefined) {
				chain_id = result.SMOKE_CHAIN_ID;
			}
    });

    setTimeout(function() {
      callback();
    }, 50 * 100);

}
/*
checkWitness: Function.
Step 1: Check witness.
Step 2: Log Missed Blocks.
Step 3: Launch updateWitness function, on reaching threshold.
*/
function checkWitness(witnessName, activeKey, backupKey, mainBrainKey, witnessLink, CreationFee, maximum_block_size, Threshold, checkRate, email, password, props, receiver, switches) {

	wls.api.getWitnessByAccount(witnessName, function (err, res) {
		if (err) {
			throw new Error(err);
		} else {
			process.stdout.write('Total Missed = '.yellow.bold + res.total_missed.toString().yellow.bold + " ");
			setTimeout(function() {

				process.stdout.write("	Checked @: ".green.bold + new Date().toString().green.bold);
				process.stdout.cursorTo(0);

	}, 5000);

		if (res.total_missed >= thresh) {
			console.log("\nBlock Missed! Initiating Switchover!".red.bold);

			thresh++;
			console.log("Thresh set to: ".gray.bold+thresh.toString().magenta.bold);
			// console.log("logging 2nd time: ", password);

			updateWitness(witnessName, activeKey, backupKey, mainBrainKey, witnessLink, password, email, props, Threshold, receiver, switches);
			// console.log("Launching update with props: ".blue.bold,props);

		}
	}
})
}
/*
getThresh: Function.
Step 1: Get witness data for total_missed.
Step 2: Set threshold to 1 above total_missed.
*/
function getThresh(witnessName){
	wls.api.getWitnessByAccount(witnessName, function (err, res) {
		// console.log(res);
		thresh = res.total_missed;
		// console.log("Thresh and total missed = "+thresh);

		thresh++;
		// COMMENT OUT THIS LINE FOR TESTING.

		process.env.threshold = thresh;
		console.log("Initializing Thresh to: ".gray.bold+ process.env.threshold.magenta.bold);

});
}
/*
updateWitness: Function.
Step 1: Send Email Notification
Step 2: Get witness and check for null key.
Step 3: Update witness node to next node.
*/
	function updateWitness(witnessName, activeKey, backupKey, mainBrainKey, witnessLink, password, email, props, Threshold, receiver, switches) {
		// console.log("Props:\n", props);
		// console.log("account_creation_fee:\n", account_creation_fee);
		console.log('Function: upgradeWitness()'.green.bold);


	process.stdout.clearLine();


	process.stdout.write("\n");

	console.log("Sending Gmail notification to:".gray.bold);

	nodemailer.createTestAccount((err, account) => {
	let transporter = nodemailer.createTransport(smtpTransport({
		service: 'gmail',
		host: 'smtp.gmail.com',
		auth: {
			user: email,
			pass: password
		}
	}));
	let mailOptions = {
		from: `"${email}"`,
		to: `"${receiver}"`,
		subject: 'You missed a block, switching servers',
		text: `You missed a block at ${new Date(Date.now()).toString()}`
	};
	transporter.sendMail(mailOptions, (error, info) => {
		if (error) {
			throw new Error(error);
		}
	});
	});

	wls.api.getWitnessByAccount(witnessName, function (err, res) {

	if (err) throw new Error(err);


	if (res.signing_key === 'WLS1111111111111111111111111111111114T1Anm'){process.exit();}
	if (backupKey === res.signing_key){
		// console.log("Broadcasting Update with key: ", activeKey);
		// console.log('Logging Fee', fee);

		wls.broadcast.witnessUpdate(activeKey, witnessName, witnessLink, mainBrainKey, props, fee, function (err, res) {
		if (err) {
			throw new Error(err);
		}

//MAYBE CODE FOR SWITCH FAIL SHOULD GO HERE.

	});
	switches++;
	console.log("Switches set to: ".gray.bold + switches.toString().magenta.bold);
	console.log("Working on Server: ".gray.bold,"Backup".magenta.bold);
	console.log("Switching to: ".gray.bold, "Main".magenta.bold);
	console.log("\n");
	if (switches === 1){
		// process.exit();
	}
}


else if (mainBrainKey === res.signing_key){
	// console.log("Broadcasting Update with key: ", activeKey);
	// console.log('Logging Fee', fee);
wls.broadcast.witnessUpdate(activeKey, witnessName, witnessLink, backupKey, props, fee, function (err, res) {
	if (err) {
		throw new Error(err);
	}

});

switches++;
console.log("Switches set to: ".gray.bold + switches.toString().magenta.bold);
console.log("Working on Server: ".gray.bold, "Main".magenta.bold);
console.log("Switching to: ".gray.bold," Backup".red.bold);
console.log("\n");
if (switches === 1){
	// process.exit();
}
}
});
}
function setNodeData(address_prefix, witness_name, active_key, backup_key, mainBrain_key, witness_link, account_crceation_fee, maxifmum_block_size, check_rate, email, password, props, receiver, switches ){
	// console.log("Starting switch statement");
// 	console.log(backup_key);
// console.log(mainBrain_key);
  try {
    switch(address_prefix) {
        case 'WLS':
        // console.log("Option 1");
				fee = '0.010 WLS';
        wls.api.setOptions({ url: 'ws://188.166.99.136:8090' });
        wls.config.set('address_prefix', 'WLS');
        wls.config.set('chain_id', 'de999ada2ff7ed3d3d580381f229b40b5a0261aec48eb830e540080817b72866');
				console.log("Function: SetNodeData()".green.bold, " \nSetting ".gray.bold,"Whaleshares".magenta.bold," Environment Variables.".gray.bold);
				console.log("Fee set to: ".gray.bold, fee.magenta.bold);


            break;
        case 'SMK':
				wls = require("@smokenetwork/smoke-js");
				fee = '0.000 SMOKE';

        wls.api.setOptions({ url: 'https://rpc.smoke.io/' });
        wls.config.set('address_prefix', 'SMK');
        wls.config.set('chain_id', '1ce08345e61cd3bf91673a47fc507e7ed01550dab841fd9cdb0ab66ef576aaf0');

				console.log("Function: SetNodeData()".green.bold, " \nSetting ".gray.bold,"Smoke".magenta.bold," Environment Variables.".gray.bold);
				console.log("Fee set to: ".gray.bold, fee.magenta.bold);
            break;
        default:
        // console.log("Default");
				fee = '0.010 WLS';

        wls.api.setOptions({ url: 'ws://188.166.99.136:8090' });
        wls.config.set('address_prefix', 'WLS');
        wls.config.set('chain_id', 'de999ada2ff7ed3d3d580381f229b40b5a0261aec48eb830e540080817b72866');
				console.log("Function: SetNodeData()".green.bold, " \nSetting ".gray.bold,"Whaleshares".magenta.bold," Environment Variables.".gray.bold);
				console.log("Fee set to: ".gray.bold, fee.magenta.bold);
    }

    console.log("Logging Chain ID: ".grey.bold,wls.config.get('chain_id').magenta.bold);
		chain_id = wls.config.get('chain_id')
    console.log("Logging Prefix: ".grey.bold,wls.config.get('address_prefix').magenta.bold);
    console.log("logging Url: ".grey.bold,wls.config.get('url').magenta.bold);

  } catch (e) {} finally {
		GetChainData(function() {
			if (isRunning === false) {
				// console.log("Chain ID: ", chain_id, "\nAccount Creation Fee: ", account_creation_fee, "\nMaximum Block Size: ", maximum_block_size);
			}
			props = {
			 account_creation_fee,
			 maximum_block_size
		 };
			checkRunning();

				/*
				Set CheckWitness on interval of ten seconds.
				*/
				process.stdout.write("\n");

				setInterval(function() {

					 let threshold = parseInt(process.env.threshold);
					 let activeSafe = active_key.substring(0,5) + '********************************' +active_key.substring(active_key.length - 5, active_key.length)
					 if (devRunning === false) {
						 console.log("Function: CheckWitness()".green.bold,"\nWitness Username: "******"\nActive Key: ".grey.bold, activeSafe.magenta.bold, "\nBackup Node Key: ".gray.bold, backup_key.magenta.bold, "\n Main Node Key: ".gray.bold,
							mainBrain_key.magenta.bold, "\n wWitness Link: ".magenta.bold, witness_link.magenta.bold, "\n Account Creation Fee: ".gray.bold, account_creation_fee.magenta.bold, "\nMaximum Block Size: ".gray.bold, maximum_block_size.toString().magenta.bold, "\nNotification Email: ".gray.bold, email.magenta.bold,
						 "\nProps: ".gray.bold, JSON.stringify(props).magenta.bold,"\n");
						 devRunning = true;
					 }


					 checkWitness(witness_name, active_key, backup_key, mainBrain_key, witness_link, account_creation_fee, maximum_block_size, threshold, check_rate, email, password, props, receiver, switches);
					 // console.log("logging 1st time: ", password);
				}, 20 * 1000);
		});
	}



}