exports.id = 'db_connector';
exports.title = 'DbConnector';
exports.version = '1.0.0';
exports.group = 'Worksys';
exports.color = '#2134B0';
exports.input = 1;
exports.output = ["red", "white"];
exports.click = false;
exports.author = 'Daniel Segeš';
exports.icon = 'bolt';
exports.options = { edge: "undefined" };

exports.html = `<div class="padding">
	<div class="row">
		<div class="col-md-6">
			<div data-jc="textbox" data-jc-path="edge" data-jc-config="placeholder:undefined;required:true" class="m">DbConnector</div>
		</div>
	</div>
</div>`;

exports.readme = `# read/write data to tables`;

const instanceSendTo = {
	debug: 0,
	http_response: 1,
}

const { promisifyBuilder, makeMapFromDbResult } = require('./helper/db_helper.js');

function extractWhereParams(params)
{
  let name = params[0];
  let operator = '=';
  let value = params[1];

  if(params.length == 3)
  {
    operator = params[1];
    value = params[2];
  }

  return {name: name, operator: operator, value: value};
}

exports.install = function(instance) {

  let refFlowdata = null;//holds reference to httprequest flowdata

  instance.on("close", () => {

  })

  
  instance.on("data", async function(flowdata) {

	let params = flowdata.data.body;
	console.log("DbConnector", params);

	refFlowdata = flowdata;

	if(refFlowdata != undefined)
	{
		//make http response
		let responseObj = {};
		responseObj["type"] = "SUCESS";

		try{

			let table = params.table;
			let action = params.action;


			if(params.data != undefined)
			{
				let className = params.data.className;

				if(className == "SqlQueryBuilder")
				{
					let type = params.data.type;

					console.log("SqlQueryBuilder---->", params.data);
					
					if(type == "SELECT")
					{
						let table = params.data.queryData.tables[0].table;

						const db = TABLE(table);
						var builder = db.find();

						let result = await promisifyBuilder(builder);

						let response = {};
						response["result"] = result;
						response["success"] = true;

						responseObj["data"] = response;
		
						//console.log(responseObj);
		
						refFlowdata.data = responseObj;
						instance.send(instanceSendTo.http_response, refFlowdata);
					}					
	
					return;
				}
			}


			console.log("db_connector---->", table, action);

			//actions: read, replace, insert, delete, update...
				
			if(action == "read")
			{
				const db = TABLE(params.table);
				
				//where builder.where('age', '<', 15);
				//builder.where('id', 3403);
				
				var builder = db.find();

				//https://docs.totaljs.com/latest/en.html#api~DatabaseBuilder~builder.where
				if(params.hasOwnProperty("where"))
				{
					//optionalCan contain "=", "<=", "<", ">=", ">".
					//Default value: '='
					
					//1.["production_line", 1]
					//2. ["or", ["production_line", 1], ["production_line", 2], "end"]
					
					if (Array.isArray(params.where)) {

					  let multipleConditions = false;
										
					  if(params.where[0] == "or") multipleConditions = true;
					  if (Array.isArray(params.where[0])) multipleConditions = true;
					  
					  if(multipleConditions)
					  {
						  
						for(var i = 0; i < params.where.length; i++)
						{
						  const item = params.where[i];

						  if(item === "or") builder.or();

						  if (Array.isArray(item))
						  {
							const { name, operator, value } = extractWhereParams(item);
							builder.where(name, operator, value);
						  }

						  if(item === "end") builder.end();
						  
						}

					  }
					  else
					  {
						const { name, operator, value } = extractWhereParams(params.where);
						builder.where(name, operator, value);
					  }

					}

					/*
					if(params.where.length >=2 )
					{
						let name = params.where[0];
						let operator = '=';
						let value = params.where[1];

						if(params.where.length == 3)
						{
							operator = params.where[1];
							value = params.where[2];
						}

						builder.where(name, operator, value);
					}
					*/
				}

				if(params.hasOwnProperty("between"))
				{
					builder.between(params.between[0], params.between[1], params.between[2]);
				}

				let response = await promisifyBuilder(builder);
				responseObj["data"] = response;

				//console.log(responseObj);

				refFlowdata.data = responseObj;
				instance.send(instanceSendTo.http_response, refFlowdata);

				return;
			}

			if(action == "delete")
			{

			}

			
			if(action == "update")
			{
			//! data receiving from terminal (params)
			// {
			// 	hostname: 'localhost',
			// 	table: 'settings',
			// 	action: 'update',
			// 	body: {
			// 		rvo_name: 'terrrr',
			// 		lang: 'en',
			// 		temperature_adress: '28.427B45920702',
			// 		latitude: 48.70826502,
			// 		longitude: 17.28455203,
			// 		mqtt_host: '192.168.252.4',
			// 		mqtt_clientid: 'showroom_test_panel_led',
			// 		mqtt_username: 'xmRd6RJxW53WZe4vMFLU',
			// 		mqtt_port: 1883,
			// 		maintanace_mode: false
			// 	}
			// }
				const tableToModify = TABLE(params.table);
				const newValues = params.body;

				tableToModify.modify(newValues).make(function(builder) {

					builder.callback(function(err, response) {
						
						if(!err) 
						{
							responseObj["data"] = response;
							responseObj["tableUpdated"] = true;
							refFlowdata.data = responseObj;
							instance.send(instanceSendTo.http_response, refFlowdata);
						}
					});
				});

			}

			if(action == "replace")
			{
				//truncate table
				const db = TABLE(params.table);
				var builder = db.remove();
				db.clean();

				//insert data
				let data = params.data;

				for(let i = 0; i < data.length; i++)
				{
					//console.log(data[i]);
					db.insert(data[i]);
				}
				
				console.log("insert done");

				let responseObj = {};
				responseObj["type"] = "SUCESS";

				refFlowdata.data = responseObj;
				instance.send(instanceSendTo.http_response, refFlowdata);


			}
			


		} catch (error) {
			//console.log(error);
			responseObj["type"] = "ERROR";
			responseObj["message"] = error;

			refFlowdata.data = responseObj;
			instance.send(instanceSendTo.http_response, refFlowdata);
	  	} 
	}
  })
}


