/*
*	Script for show and edit indexes and subindexes, which included in eds file.
*   Usage: <div index="2081:1" class="tag"></div>
* 	Nedeed scripts:
*		<script src="external/jquery/jquery.js"></script>
		<script src="external/validation/jquery.validate.js"></script>
		<script src="get_set_value_tool.js"></script>
		<script src="eds_json.js.gz" charset="utf-8"></script>
*/



(function(exports) {
	let eds_object
	let get_set_value

	exports.get_set_init = function()
	{
		get_set_value = new GetSetValue()
	}

	exports.on_page_loading_finished = function()
	{
		get_set_value = new GetSetValue()
		common.add_multiply_templates()
		$(".tab-class").tabs()
		$("#boyan").accordion(
		{ 
			heightStyle: 'content',
			header: '.accordion-header',
			active: 0,
			beforeActivate: function( event, ui )
			{
				get_set_value.clear_send_query()
			},
			activate: function( event, ui )
			{
				user.reload_page()
			},

		})
		$("#boyan").accordion( "option", "collapsible", true )

		
		/*$('.can_hide').each(function( index )
		{
			var form = $(this).children('.value_td').children('.accordion_tag, .tag').children('.apply_form')
			if ($(form).hasClass('empty')) 
			{ 
				$(this).hide() 
				
			}
		})*/
		
		$('.empty').each(function( index )
		{ 
			console.log(this)
			//$(this).parent().parent().parent().hide() 
			
		})

		hide_indexes(configuration.hide_fields_indexes)
		$("div[index='1001:0']").hide()

		
		$(document).on('click', '.autoupdate', function()
		{
			get_set_value.on_autoupdate_click()
		})
		$(window).focus(function() //Во вкладке
		{
			get_set_value.on_windows_focus()
		})
		$(window).blur(function() //Покинули вкладку
		{
			get_set_value.on_windows_blur()
		})
	}

	exports.show_main_view_intreface = function show_main_view_intreface()
	{
		let autoupdate_label = $('<label>')
		autoupdate_label.append('<label class="autoupdate"><span></span></label>')
		autoupdate_label.append('<div>\u00a0</div>')
		autoupdate_label.append(`<div id="autoupdate">${l100n.localize_string("autoupdate")}</div>`)
		let left_td_1 = $('<td style="width: 100%">').append(autoupdate_label)
		let right_td_1 = $('<td>').append('<div id="language"></div>')
		let left_td_2 = $('<td style="width: 100%">')
		left_td_2.append(`<div id="access_control">${l100n.localize_string("access_control")}</div>`)
		left_td_2.append('<div>\u00a0</div>')
		left_td_2.append('<div index="2001:9" class="tag"></div>')
		left_td_2.append('<div>\u00a0</div>')
		left_td_2.append('<div id="login"></div>')
		let right_td_2 = $('<td>')
		let left_td_3 = $('<td style="width: 100%">').append(`<a href="raw_access.html" target="_blank" id="Expert_page">${l100n.localize_string("Expert_page")}</a>`)
		let log_view_link = $(`<a href="log_view.html" target="_blank" id="log_view_link">${l100n.localize_string("Event log")}</a>`).hide()
		let left_td_4 = $('<td style="width: 100%">').append(log_view_link)
		let right_td_3 = $('<td>')//.append('<div id="errors_info"></div>')
		let right_td_4 = $('<td>')//.append('<div id="errors_info"></div>')

		let tr1 = $('<tr>').append(left_td_1).append(right_td_1)
		let tr2 = $('<tr>').append(left_td_2).append(right_td_2)
		let tr3 = $('<tr>').append(left_td_3).append(right_td_3)
		let tr4 = $('<tr>').append(left_td_4).append(right_td_4)

		$("#view").append($('<table>').append(tr1).append(tr2).append(tr3).append(tr4))

		if (configuration.show_log_view == true) 
		{
			$("#log_view_link").show()
		}

		l100n.show_locale()
		add_login_dialog()
	}

	exports.show_errors_info = function()
	{
		let hw_tr = common.form_tag_tr_param({name: l100n.localize_string("HW Error Flags"), index: 0x2001, sub: 12, simple_tag: true})
		let sw_tr = common.form_tag_tr_param({name: l100n.localize_string("SW Error Flags"), index: 0x2001, sub: 13, simple_tag: true})
		$("#errors_info").append($('<table>').append(hw_tr).append(sw_tr)).hide()
	}

	function hide_indexes(hide_fields_indexes)
	{   
		//console.log(hide_fields_indexes)
		if (hide_fields_indexes)
		{
			hide_fields_indexes.forEach(function(item, index, array) 
			{
				if (item.type === "one_field")
				{
					let index = Number(item.index).toString(16).toUpperCase()
					let sub = item.sub			
					//console.log(`.tag[index="${index}:${sub}"]`)
					$(`.accordion_tag[index="${index}:${sub}"], .tag[index="${index}:${sub}"]`).parent().parent().hide()
				}
				else if (item.type === "multy_sub")
				{
					for (let number = 1; number <= item.count; number++)
					{
						let index = Number(item.index).toString(16).toUpperCase()
						let sub = number			
						//console.log(`.tag[index="${index}:${sub}"]`)
						$(`.accordion_tag[index="${index}:${sub}"], .tag[index="${index}:${sub}"]`).parent().parent().hide()
					}
				}
				else if (item.type === "multy_index")
				{
					for (let number = 1; number <= item.count; number++)
					{
						let index = (Number(item.index) + item.index_multiply*(number-1)).toString(16).toUpperCase()
						let sub = item.sub
						//console.log(`.tag[index="${index}:${sub}"]`)
						$(`.accordion_tag[index="${index}:${sub}"], .tag[index="${index}:${sub}"]`).parent().parent().hide()
					}
				}
				else
				{
					console.log("wrong type")
				}
			})
		}
	}

	function add_login_dialog()
	{
		let login_button = ($(`<input type="submit" value="${l100n.localize_string("Login")}" id="login_button">`))
		$("#login").append(login_button)
		$(document).on('click', '#login_button', function()
		{
			$("#login_dialog").dialog('open')
		})

		let dialog = $('<div id="login_dialog">').attr('title', l100n.localize_string("Login_header"))
		dialog.append('<div index="2002:2" class="tag"></div>')
		dialog.dialog({
			resizable: false,
			//height: 151,
			//width: 233,
			autoOpen: false,
			modal: false,
			position: { my: "left top", at: "left bottom", of: "#login" },
		})
	}

	exports.load_page = function()
	{
		const eds_script = utils.load_script('eds.js')
		Promise.all([
			eds_script
		])
		.then(() => eds.get_eds_object())
		.then(eds_obj => {
			eds_object = eds_obj

			//get_set_value = new GetSetValue()
			let request_data = get_request_data(".accordion_tag, .tag") //get all tag
			//console.log(request_data)
			get_set_value.set_request_data(request_data, ".accordion_tag .value, .tag .value")
			

			tags_to_input_transform(".accordion_tag, .tag")
			get_set_value.send_query()

			l100n.localize_all_pages()
		})
	}

	exports.reload_page = function()
	{
		//get_set_value = new GetSetValue()
		let request_data = get_request_data(".ui-accordion-content-active .accordion_tag,  .tag") //get only active
		//console.log(request_data)
		get_set_value.set_request_data(request_data, ".ui-accordion-content-active .accordion_tag .value, .tag .value")	
	
		tags_to_input_transform(".ui-accordion-content-active .accordion_tag,  .tag")
		get_set_value.send_query()
	}

	function get_request_data(tags)
	{
		let request_data = []

		$(tags).each(function(tag_index, tag_item) 
		{
			let index = $(tag_item).attr('index')
			let index_arr = index.split(':')
			if (index_arr[0] != "" && index_arr[1] != "")
			{
				if ((eds_object[index_arr[0]] != undefined) && (eds_object[index_arr[0]].subs != undefined))
				{
					//console.log(eds_object[index_arr[0]])
					//console.log(eds_object['index_list'][index_arr[0]][$(tag_item).attr('index')])
					request_data[tag_index] = eds_object[index_arr[0]].subs[index_arr[1]]
				}
				else
				{
					console.log(`Index: 0x${index_arr[0]}_${index_arr[1]} is absent in eds file`)
				}
			}
		})

		return request_data
	}

	function tags_to_input_transform(tags)
	{
		$(tags).each(function(tag_index, tag_item) 
		{
			if ($(tag_item).hasClass('loaded'))
			{
				return; // this is equivalent of 'continue' for jQuery loop
			}

			let class_type = ""
			if ($(tag_item).hasClass("ro"))
			{
				class_type = "ro"
			}
			else if ($(tag_item).hasClass("boolean_input"))
			{
				class_type = "boolean_input"
			}
			else if ($(tag_item).hasClass("boolean_output"))
			{
				class_type = "boolean_output"
			}
			else if ($(tag_item).hasClass("boolean_alarm"))
			{
				class_type = "boolean_alarm"
			}

			let cell = get_set_value.get_cell(tag_index, class_type)
			$(tag_item).empty()
			$(tag_item).append(cell)
			$(tag_item).addClass('loaded')
		})
	}
	
	$(document).on('value_loaded', 'div[tb_index="2001_12"]', function( e )
	{
		if ($(this).hasClass('no_error'))
		{
			$(this).parent().parent().parent().parent().hide() 
		}
		else
		{
			$(this).parent().parent().parent().parent().show()
		}
	})

	$(document).on('value_loaded', 'div[tb_index="2001_13"]', function( e )
	{   
		if ($(this).hasClass('no_error'))
		{
			$(this).parent().parent().parent().parent().hide()
		}
		else
		{
			$(this).parent().parent().parent().parent().show()
		}
	})

	
	$(document).on("get_value_completed", function(event) 
	{
		$('.scaled').each(function( index ) {
			let scaling_index = $(this).attr('scaling_index')
			let scaling_sub = $(this).attr('scaling_sub')
			let offset_index = $(this).attr('offset_index')
			let offset_sub = $(this).attr('offset_sub')
		
			let scaling_input = $(`input[tb_index="${scaling_index}_${scaling_sub}"]`)
			let offset_input = $(`input[tb_index="${offset_index}_${offset_sub}"]`)

			let scaled = false
			if (parseFloat(scaling_input.val()) != 1)
			{
				scaled = true
			}
			if (parseFloat(offset_input.val()) != 0)
			{
				scaled = true
			}

			if (scaled)
			{
				$(this).addClass("on")
			}
			else
			{
				$(this).removeClass("on")
			}
		})
	})
})(this.user = {})