(function(exports) {
exports.show_main_view_intreface = function show_main_view_intreface()
{
    var 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>`)
    var left_td_1 = $('<td style="width: 100%">').append(autoupdate_label)
    var right_td_1 = $('<td>').append('<div id="language"></div>')
    var 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>')
    var right_td_2 = $('<td>')
    var left_td_3 = $('<td style="width: 100%">').append(`<a href="raw_access.html" target="_blank" id="Expert_page">${l100n.localize_string("Expert_page")}</a>`)
    var right_td_3 = $('<td>')//.append('<div id="errors_info"></div>')

    var tr1 = $('<tr>').append(left_td_1).append(right_td_1)
    var tr2 = $('<tr>').append(left_td_2).append(right_td_2)
    var tr3 = $('<tr>').append(left_td_3).append(right_td_3)

    $("#view").append($('<table>').append(tr1).append(tr2).append(tr3))
    l100n.show_locale()
    add_login_dialog()
}

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

exports.add_multiply_templates = function()
{
    if (configuration.get_multiply_templates())
    {
        configuration.get_multiply_templates().forEach(function(block, i, arr) {
            //console.log(block)
            if (block.type == "index multiply")
            {
                let count = block.count
                let index_multiply = block.multiply_coefficient
                block.templates.forEach(function(item, i, arr) {
                    for (let number = 1; number <= count; number++)
                    {
                        let index_arr = item.index.split('_')
                        let index = (Number("0x" + index_arr[0]) + (number - 1)*index_multiply).toString(16).toUpperCase()
                        let sub = index_arr[1]
                        let item_clone = {};
                        Object.assign(item_clone, item)
                        item_clone.index = `${index}_${sub}`
                        configuration.add_template(item_clone)
                    }
                })
            }
            else if (block.type == "subindex multiply")
            {
                let count = block.count
                block.templates.forEach(function(item, i, arr) {
                    for (var number = 1; number <= count; number++)
                    {
                        let index = Number("0x" + item.index).toString(16).toUpperCase()
                        let item_clone = {};
                        Object.assign(item_clone, item)
                        item_clone.index = `${index}_${number}`
                        configuration.add_template(item_clone)
                    }
                })
            }
            else
            {
                console.log("illegal multi templates type")
            }
        })      
    }
    //console.log(configuration.data_type_template())
}

exports.on_page_loading_finished = function()
{
    common.add_multiply_templates()
    $(".tab-class").tabs();
    $("#boyan").accordion({ heightStyle: 'content', header: '.accordion-header', active: 0})
    $("#boyan").accordion( "option", "collapsible", true )
    
    $('.can_hide').each(function( index )
    {
        var form = $(this).children('.value_td').children('.tag').children('.apply_form')
        if ($(form).hasClass('empty')) { $(this).hide() }
    })
    hide_indexes(configuration.hide_fields_indexes)
    $("div[index='1001:0']").hide()
}

exports.form_tag_tr = function(param_name, eds_index, eds_subindex)
{ 
	return exports.form_tag_tr_param({name: param_name, index: eds_index, sub: eds_subindex})
}

exports.form_tag_tr_param = function(param) 
{ 
    let tr = $('<tr class="can_hide">')
    let td = $('<td>').text(param.name)
    if (param.tab)
    {
        td.addClass('name')
    }
	let div = $('<div>').addClass("tag").attr({"index": `${param.index.toString(16).toUpperCase()}:${param.sub}`})
    if ("type" in param)
	{
		div.addClass(param.type)
	}
    tr.append(td).append($('<td>').append(div))//.addClass("name"))
    return tr
}

exports.form_tag_tr2 = function(param_name, eds_index, eds_subindex, param_name2, eds_index2, eds_subindex2) 
{ 
	return exports.form_tag_tr2_param({name: param_name, index: eds_index, sub: eds_subindex, type: ""},
							{name: param_name2, index: eds_index2, sub: eds_subindex2, type: ""})
}

exports.form_tag_tr2_param = function(param1, param2)
{
    var tr = $('<tr class="can_hide">').append($('<td>').text(param1.name))//.addClass("name"));
	var div = $('<div>').addClass("tag").attr({"index": `${param1.index.toString(16).toUpperCase()}:${param1.sub}`});
	if ("type" in param1)
	{
		div.addClass(param1.type)
	}
    tr.append($('<td>').append(div))//.addClass("name"));
	//tr.append($('<td>'))//.addClass('empty_space'));
	if (param2.name != "")
	{
		tr.append($('<td>').text(param2.name).addClass("name"));
	}

	var div2 = $('<div>').addClass("tag").attr({"index": `${param2.index.toString(16).toUpperCase()}:${param2.sub}`});
	if ("type" in param2)
	{
		div2.addClass(param2.type)
	}
    tr.append($('<td>').append(div2))//.addClass("name"));
    return tr;
}

exports.form_tag_tr3 = function(param_name, eds_index, eds_subindex, param_name2, eds_index2, eds_subindex2, param_name3, eds_index3, eds_subindex3) 
{ 
	return exports.form_tag_tr3_param({name: param_name, index: eds_index, sub: eds_subindex, type: ""},
							{name: param_name2, index: eds_index2, sub: eds_subindex2, type: ""},
                            {name: param_name3, index: eds_index3, sub: eds_subindex3, type: ""})
}

exports.form_tag_tr3_param = function(param1, param2, param3)
{
    var tr = $('<tr class="can_hide">').append($('<td>').text(param1.name))//.addClass("name"));
	var div = $('<div>').addClass("tag").attr({"index": `${param1.index.toString(16).toUpperCase()}:${param1.sub}`});
	if ("type" in param1)
	{
		div.addClass(param1.type)
	}
    tr.append($('<td>').append(div))//.addClass("name"));
	//tr.append($('<td>'))//.addClass('empty_space'));
	if (param2.name != "")
	{
		tr.append($('<td>').text(param2.name).addClass("name"));
	}

	var div2 = $('<div>').addClass("tag").attr({"index": `${param2.index.toString(16).toUpperCase()}:${param2.sub}`});
	if ("type" in param2)
	{
		div2.addClass(param2.type)
	}
    tr.append($('<td>').append(div2))//.addClass("name"));

    var div3 = $('<div>').addClass("tag").attr({"index": `${param3.index.toString(16).toUpperCase()}:${param3.sub}`});
	if ("type" in param3)
	{
		div3.addClass(param3.type)
	}
    tr.append($('<td>').append(div3))//.addClass("name"));
    return tr;
}

exports.form_tag_divide_tr = function(param_name, eds_index_num, eds_subindex_num, eds_index_den, eds_subindex_den)
{
    var tr = $('<tr class="can_hide">').append($('<td>').text(param_name).addClass("name"));
    var table = $('<table>');
    var div1 = $('<div>').addClass("io").addClass("tag").attr({"index": `${eds_index_num.toString(16).toUpperCase()}:${eds_subindex_num}`});
    var div2 = $('<div>').addClass("io").addClass("tag").attr({"index": `${eds_index_den.toString(16).toUpperCase()}:${eds_subindex_den}`});
    table.append($('<tr>').append(($('<td style="border-bottom-color: black">').append(div1))))
    table.append($('<tr>').append(($('<td>').append(div2))))
    tr.append($('<td>').append(table));
    return tr;
}

exports.response_ready = function(response_text)
{
	return new Promise(function(resolve, reject) {
		let values = utils.get_response_values_from_text(response_text)
		resolve(values);
	})
}


function hide_indexes(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}"]`)
                $(`.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}"]`)
                    $(`.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}"]`)
                    $(`.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" },
    })
}

$(document).on('value_loaded', 'div[tb_index="1001_0"]', function( e )
{
    let device_error = $(this).text()
    if (device_error > 0)
    {
        $('.device_status').addClass('device_error')
        $('#errors_info').show()
    }
    else
    {
        $('.device_status').removeClass('device_error')
        $('#errors_info').hide()
    }

    $(this).removeClass('value_loaded')
})

$(document).on('value_loaded', '.board_status', function( e )
{
    let board = $(this).children('form').children('div.value')
    let board_error = board.text()
    let status_index = $(this).attr('index')
    if (board_error > 0)
    {
        $(`div[status_index="${status_index}"]`).addClass('device_error')
    }
    else
    {
        $(`div[status_index="${status_index}"]`).removeClass('device_error')
    }
    $(this).removeClass('value_loaded')
})

})(this.common = {})
