(function(exports) {

exports.show = async function ()
{
    let ul = $('<ul id="device_info_ul">')
    let table = $('<table id="device_info_table">')
    let tab_body = []

    ul.append($(`<li><a href="#info_tab">${l100n.localize_string("device_info")}</a></li>`))
    
    tab_body[0] = $(`<tbody id="info_tab">`).addClass('nowrap_td').addClass('data_td')

    tab_body[0].append(common.form_tag_tr(l100n.localize_string("Product_Code"), 0x2000, 2))
    tab_body[0].append(common.form_tag_tr(l100n.localize_string("Revision_number"), 0x2000, 3))
    tab_body[0].append(common.form_tag_tr(l100n.localize_string("uid"), 0x2000, 4))
    tab_body[0].append(common.form_tag_tr(l100n.localize_string("sw_version"), 0x2000, 6))
    tab_body[0].append(`
        <tr class="can_hide">
            <td class="name" id="time">Time: </td>
            <td>
                <div index="2081:1" class="tag ro" style="display: inline-block;"></div>&nbsp;&nbsp;
                <div id="datetime_edit"></div>
                <div id="system_time_setting"></div>
            </td>
        </tr>`)
        
    tab_body[0].append(common.form_tag_tr(l100n.localize_string("battery_voltage"), 0x2001, 5))
    tab_body[0].append(common.form_tag_tr(l100n.localize_string("App_version"), 0x5000, 3))
    tab_body[0].append(common.form_tag_tr(l100n.localize_string("command"), 0x2002, 1))
    tab_body[0].append(common.form_tag_tr(l100n.localize_string("restore_default_settings"), 0x1011, 1))
    //tab_body[0].append(`<tr><td class="name" id="download_dump_tr"></tr>`)
    // Если раскомментировать не будет работать диалоговое окно login, так как дублируется индекс
    //tab_body[0].append(common.form_tag_tr(l100n.localize_string("password"), 0x2002, 2)) 
    table.append(tab_body[0])

    ul.append($(`<li><a href="#addons_tab">${l100n.localize_string("addons_tab")}</a></li>`))
    await fetch('./addons/addons_desc.json')
    .then((response) => response.json())
    .then((json) => {
        tab_body[1] = $(`<tbody id="addons_tab">`).addClass('nowrap_td').addClass('data_td')
        $.each(json, function(index, item)
        {
            if (item.href && item.name)
            {
                let link = `<a href="${item.href}" target="_blank">${l100n.localize_string(item.name)}</a>`
                let tr = $('<tr>').append($('<td>').append(link))
                tab_body[1].append(tr)
            }
            else
            {
                console.log('Ошибка в объекте addons_desc.json')
            }
        })

        table.append(tab_body[1])
    })

    let tabs_div = $('<div class="tab-class">').append(ul).append(table)
    let h3 = $('<h3>').append(l100n.localize_string("Device Description"))
    let board_head = $('<div>').addClass("device_status").addClass("accordion-header")
    board_head.append('<div index="2000:1" class="tag div_in_header"></div>')
	let board_body = $('<div>').addClass("accordion-body").append(tabs_div)
    board_body.append('<div index="1001:0" class="tag"></div>')
    //board_body.append('<div id="board_head"></div>')
	$("#device_info").append(h3).append(board_head).append(board_body)

    //show_dump_button()
    add_datetime_edit()
    add_password_change_dialog()   
}

function add_datetime_edit()
{
    let system_time_setting_button = ($(`<input type="submit" value="${l100n.localize_string("Synchronize")}" id="system_time_setting_button">`))
	$("#system_time_setting").append(system_time_setting_button)
    $(document).on('click', '#system_time_setting_button', function()
    {
        if (confirm(l100n.localize_string("system_time_setting_confirm_question")))
        {
            let d = new Date();
            let zone_offset = d.getTimezoneOffset();
            let value = Date.now()/1000 - zone_offset * 60
            /*let query = `/set_od_data.form?0x2081_1=${value}`
            button_command_xhr.open('GET', query, true)
            button_command_xhr.send()*/
            let query = `/set_od_data.form?0x2081_1=${value}`
            return fetch(query).then(response => {})
            .catch(function(error) {
                //console.log(query)
                alert(`${l100n.localize_string('Request failed')}: ${error} "${query}"`)
            })
        }

        $("#date_input").removeClass('changed')
        $("#time_input").removeClass('changed')
    })

    let datetime_edit_button = ($(`<input type="submit" value="${l100n.localize_string("Set datetime manually")}" id="datetime_edit_button">`))
	$("#datetime_edit").append(datetime_edit_button)
    $(document).on('click', '#datetime_edit_button', function()
    {
        $("#datetime_edit_dialog").dialog('open')
    })

    let dialog = $('<div id="datetime_edit_dialog">').attr('title', l100n.localize_string("Set datetime manually"));
    dialog.append('<span class="ui-helper-hidden-accessible"><input type="text"/></span>')
    dialog.append($('<div index="2081:1" class="tag">'))
    dialog.dialog({
        resizable: false,
        //height: 151,
        //width: 233,
        autoOpen: false,
        modal: false,
        position: { my: "left top", at: "left bottom", of: "#datetime_edit_button" },
    })
}

function add_password_change_dialog()
{
    let dialog = $('<div id="pass_change_dialog">').attr('title', l100n.localize_string("Change password."))
    let form = $('<form>')
    form.append($('<input type="password" class="password" name="password" id="password_confirm" value="">'))
    form.append($('<label>\u00A0</label>'))
    form.append($('<input type="password" class="password" name="password2" id="password_confirm2" value="">'))
    form.append($('<label>\u00A0</label>'))
    form.append($('<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">'))
    form.validate()
    dialog.append(form)
    dialog.dialog({
        resizable: false,
        //height: 151,
        //width: 233,
        autoOpen: false,
        modal: false,
        position: { my: "left top", at: "right bottom", of: `[tb_index='2002_1']` },
        buttons: [{
                text: l100n.localize_string("Ok"),
                click: change_password},
            {
                text: l100n.localize_string("Cancel"),
                click: function() {
                    $(this).dialog("close");}
            }]
    })
    //$('.ui-dialog-titlebar-close').hide()
    form = dialog.find( "form" ).on( "submit", function( event ) {
        event.preventDefault()
        change_password()
    })
}

function change_password()
{
    if ($('#password_confirm').val() != $('#password_confirm2').val())
    {
        alert(l100n.localize_string('Passwords are different.'))
    }
    else if ($('#password_confirm').hasClass('error') &&
        $('#password_confirm2').hasClass('error'))
    {
        alert(l100n.localize_string("Invalid data format."));
    }
    else
    {
        var index_number = '2002_2'
        var new_value = utils.pass2ascii($('#password_confirm').val())
        var query = '/set_od_data.form?'
        query += utils.get_set_od_data_query_unit(index_number, new_value)                                                           

        return fetch(query).then(response => {
            if (response.ok)
            {
                alert(l100n.localize_string('Password are changed.'))
                $('#password_confirm').val('')
                $('#password_confirm2').val('')
                $("#pass_change_dialog").dialog("close")
            }
        }).catch(function(error) {
            //console.log(query)
            alert(`${l100n.localize_string('Request failed')}: ${error} "${query}"`)
        })
    }
}

/*show_dump_button = function()
{
    let download_link = `<a href="download_od_values_dump.html" target="_blank">${l100n.localize_string("download_dump")}</a>`
    let download_td = $('<td>').append(download_link)
    let upload_link = `<a href="upload_od_values_dump.html" target="_blank">${l100n.localize_string("upload_dump")}</a>`
    let upload_td = $('<td>').append(upload_link)
    $("#download_dump_tr").append(download_td).append(upload_td)
}*/

})(this.device_info = {})

$.validator.addMethod("password", function(value, element)
{
	var re = new RegExp("^[0-9'.\\s]{4}$")
    return this.optional(element) || re.test(value)
}, l100n.localize_string("validator_pass"))

$.validator.addClassRules("password", {required: false, password: true })