var fileId = 0;
var uploadType = parent.uploadType;
var fw_name;
var selectedUploadType = "";
let fwValue = new URLSearchParams(window.location.search).get("fw");

$(window).bind("load", function () {
    parent.$('#divFileUpload').removeAttr("tabindex");
    defaulting(true);
    $("#spinner").hide();

    if(fwValue == 'open'){
        $("#fwlist-tab").trigger("click");
    }

});

$("#fwlist-tab, #fwupload-tab, #firmware-boot-tab").on("click", function (e) {
    e.preventDefault();

    let container = $(".customClass"); // scrollable container
    let target = $(this).closest("li"); // scroll to the clicked li

    container.animate({
        scrollTop: target.offset().top - container.offset().top + container.scrollTop()
    }, 1000);
});

function Request() {
    var request = {
        url: "",
        parameters: {},
        Type: ""
    };
    return request;
}
function CallPythonService(request, tasktype) {
    request.parameters.uuid = parent.uuid;
    $.ajax({
        type: "Get",
        url: request.url,
        contentType: 'application/json',
        dataType: 'json',
        headers: { 'Access-Control-Allow-Origin': '*' },
        data: request.parameters,
        success: function (response) {
            BindResponseData(request.Type, tasktype, response);
        },
        error: function (ex) {
            if (!parent.isProduction) {
                console.log(ex);
            }
        }
    });
}
function BindResponseData(Type, tasktype, response) {
    if (Type == 'hardwareAdminOperations') {

        $("#spinner").hide();
        if(tasktype == "delete"){
            window.parent.swal(response.description, "", response.status == "success" ? "success" : "error");
            if(response.status == "success") ReadDir();
        }
        else if (tasktype == "factoryReset"){
            window.parent.swal(response.description, "", response.status == "success" ? "success" : "error");
            if(response.status == "success") window.parent.location.href = "index.html";
        }
        else if (response.status == "success") {
            setTimeout(function () {
                window.parent.swal({
                    title: "ACTIVATE", //response.description,
                    text: "This operation will take several minutes to complete, after ACTIVATE you will be returned to the home screen, please wait till the system restarts and show software status as good.",
                    type: response.status
                }, function () {
                    if (response.status == "success") {
                        window.parent.location.href = "index.html";
                    }
                    console.log("onConfirmation")
                });
            }, 1000);

        }
        else {
            window.parent.swal(response.description, "", "error")
        }
    }

};
$("input[type='file']").on('change', function () {
    $('zip_filename').css("color", "#00b4f0")
    var selectedObj = $(this);
    //Get count of selected files
    var countFiles = $(this)[0].files.length;
    var filePath = $(this)[0].value;
    var extn = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
    //console.log("change function");
    if (countFiles > 0) {
        var filename = $(this)[0].files[0].name;
        fw_name = filename
        filename = "<strong>Filename: </strong>" + filename;
        //$('.help-block').hide();
        $("input[type='file']").each(function (i, obj) {
            if (!selectedObj.is(obj)) {
                $(obj).attr('disabled', 'disabled');
                $(obj).siblings('button').attr('disabled', 'disabled').addClass('gray-button');
                $(obj).val(null);
            }
        });
        if ($(this).attr('uploadType') === 'zip') {
            selectedUploadType = 'zip';
            $('zip_filename').html(filename);
        }
        else {
            console.log("$(this).attr('uploadType'): ", $(this).attr('uploadType'));
            selectedUploadType = 'iso';
            $('iso_filename').html(filename);
        }
        $('#btnSubmit').attr('disabled', false);
        $('#btnReset').attr('disabled', false);
        $('#btnSubmit').removeClass('gray-button');
        $('#btnReset').removeClass('gray-button');
        $('#btnSubmit').addClass('red-button');
        $('#btnReset').addClass('red-button');
        parent.$('#divResponse_').html('Please choose the package and click on upload button').removeClass('alert-danger').addClass('alert-success');
    }
});

function resetButton() {
    $('.help-block').show();
    prevPer = 0;
    $('#percentSpan').html('0%');
    $('#percentDiv').removeClass().addClass('c100 p0');
    $('#btnSubmit').html('Upload').addClass('gray-button').attr('disabled', 'disabled');
    $('#btnReset').addClass('gray-button').attr('disabled', 'disabled');
    $('#btnActivate').addClass('gray-button').attr('disabled', 'disabled');
    $("#btnActivate").attr("onclick", "");
    $('.isoBlock').html('Upload the OS upgrade .iso file here');
    $('.zipBlock').html('Upload the OS patch .zip file here');
    $('input[type="file"]').attr('disabled', false);
    $("input[type='file']").each(function (i, obj) {
        $(obj).val(null);
    });
    $('.choosefilebuttons').removeClass('gray-button').addClass('red-button').attr('disabled', false);
    $('.filename').html('')
    parent.$('#divResponse_').html('Please choose the package and click on upload button').removeClass('alert-danger').addClass('alert-success');
}

function disableUnusedFileUpload() {
    $("input[type='file']").each(function (i, obj) {
        if ($(obj)[0].files.length < 1) {
            $(obj).attr('disabled', 'disabled');
            $(obj).siblings('button').attr('disabled', 'disabled').addClass('gray-button');
            $(obj).val(null);
        }
    });
}

var prevPer = 0;
$(function () {
    $('zip_filename').css("color", "#00b4f0")
    $('form').ajaxForm({
        beforeSend: function () {
            var percentVal = '0%';
            keepFading($("#percentDiv"));
        },
        uploadProgress: function (event, position, total, percentComplete) {
            //$('.progress').css('display','block');
            $("#pageloader").fadeIn();
            var percentVal = percentComplete + '%';
            $('#percentDiv').removeClass('p' + prevPer).addClass('p' + percentComplete);
            $('#percentSpan').html(percentVal);
            prevPer = percentComplete;

        },
        complete: function (xhr) {
            $("#pageloader").fadeOut();
            var response = JSON.parse(xhr.responseText);
            // console.log(response,response.status)
            $('.isoBlock').html('Upload the package iso file here');
            $('.zipBlock').html('Upload the package zip file here');
            if (selectedUploadType == 'iso') $('iso_filename').html(response.description);
            else {
                if (response.status == 'fail') {
                    $('zip_filename').css("color", "red")
                }
                else {
                    $('zip_filename').css("color", "#00b4f0")
                }
                $('zip_filename').html(response.description);
            }
            $('.help-block').show();
            defaulting(false, response, response.status);
        }
    });
});

function successfullyUploadedText(path) {
    var str = `<a href="` + path + `" download="License.txt" id="aDownload"
        title="Click here to download uploaded license">License
    </a>
    uploaded successfully!
    `;
    return str;
}

function defaulting(bool, response = {}, status = '') {
    if (bool) {
        prevPer = 0;
        $('#percentSpan').html('0%');
        $('#percentDiv').removeClass().addClass('c100 p0');

        $('#btnSubmit').html('Upload').addClass('gray-button').attr('disabled', 'disabled');
        $('#btnReset').addClass('gray-button').attr('disabled', 'disabled');
        $('#btnActivate').addClass('gray-button').attr('disabled', 'disabled').attr("onclick", "");

        $('input[type="file"]').attr('disabled', false);
        $('.choosefilebuttons').removeClass('gray-button').addClass('red-button').attr('disabled', false);
        $('.filename').html('')

        parent.$('#divResponse_').html('Please choose the package and click on upload button').removeClass('alert-danger').addClass('alert-success');

        $('.help-block').show();
    }
    else {
        prevPer = 0;
        $('#percentSpan').html('0%');
        $('#percentDiv').removeClass().addClass('c100 p0');

        $('#btnSubmit').html('Uploaded').addClass('gray-button').attr('disabled', 'disabled');
        $('input[type="file"]').attr('disabled', 'disabled');

        if (status == 'success') {
            parent.$('#divResponse_').html('Success! File uploaded successfully').removeClass('alert-danger').addClass('alert-success');
            if (selectedUploadType == 'iso') {
                $("#btnActivate").attr("onclick", "hardwareAdminOperations('reboot')");
            }
            else {
                $("#btnActivate").attr("onclick", "hardwareAdminOperations('restart')");
            }
            $('#btnActivate').removeClass('gray-button').addClass('red-button').attr('disabled', false);
        }
        else if (status !== '') {
            parent.$('#divResponse_').html('Error! package couldn\'t be uploaded').removeClass('alert-success').addClass('alert-danger');
            $('#btnSubmit').html('Upload').addClass('gray-button').attr('disabled', false);
            $('input[type="file"]').attr('disabled', false);
        }
        disableUnusedFileUpload();
        $('.help-block').show();
    }
}

function keepFading($obj) {
    $obj.animate({ opacity: 0.5 }, 1000, "swing").animate({ opacity: 1 }, 1000, function () {
        keepFading($obj);
    });
}

var uploadType = "";
function hardwareAdminOperations(tasktype, name = fw_name) {
    if (tasktype === "reboot" || tasktype === "restart" || tasktype == "activate" || tasktype == "delete" || tasktype == "factoryReset") {
        swal({
            title: "Please enter the password",
            html: true,
            text: "<input type='password' class='form-control' id='confirm-password' placeholder='Password'>",
            showCancelButton: true,
            closeOnConfirm: false,
            closeOnCancel: false,
            width: 100,
            animation: "slide-from-top"
        },
            function (isConfirm) {
                if (isConfirm) {
                    $("#spinner").show();
                    var password = $('#confirm-password').val();
                    var sessionData = JSON.parse(sessionStorage.getItem("sessionData"));
                    var user_id = sessionData['Userid'];
                    var request = new Request();
                    request.url = "../cgi/cgi_Hardware_Admin.py";
                    request.parameters = { "RequestType": tasktype, "password": password, "fw_name": name };
                    request.Type = "hardwareAdminOperations";
                    CallPythonService(request, tasktype);
                } else {
                    parent.swal("Cancelled", "", "error");
                }
            });
    }
}
ReadDir()
$(document).on('click', 'input[name="fw_name"]', function () {

     $(".deleteFwBtn").hide(); // hide all
    $(this).closest("tr").find(".deleteFwBtn").show(); // show selected
});


function ReadDir() {
    $.ajax({
        type: "Get",
        url: "../cgi/cgi_Hardware_Admin.py",
        contentType: 'application/json',
        dataType: 'json',
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        data: { RequestType: "getFw" },
        success: function (response) {
            $("#fwdata").empty();
            $("#factory_path").html(response?.factory_files ? response?.factory_path : "N/A");
            response.dirArray.map((item, index) => {
                let radio_disabled = item.status != "True" ? "" : "disabled";
                $("#fwdata").append(`
                    <tr>
                        <td><input type="radio" value="${item.fw_name}" id="radio_${index}" name="fw_name" ${radio_disabled}></td>
                        <td>${moment(item.upload_date).format("DD, MMMM YYYY")}</td>   
                        <td>${item.fw_name}</td>   
                        <td>${moment.utc(item.last_activated, "YYYY-MM-DD HH:mm:ss").local().format("MMMM DD, YYYY HH:mm:ss")}</td>   
                        <td class="button-cell">
                            <div class="d-flex justify-content-between">
                                <div>
                                    ${item.status != "True" ? `<button class="btn btn-sm btn-primary" style="width : 80px" onclick="hardwareAdminOperations('activate','${item.fw_name}')" data-toggle="tooltip" data-placement="top" title="Activate">Activate</button>` : `<button class='btn btn-sm btn-warning disabled' style="cursor:not-allowed;width : 80px;" disabled>Activated</button>`}   
                                </div>
                                <div>
                                    <button class="btn btn-sm btn-danger deleteFwBtn" style="width : 80px" data-toggle="tooltip" data-placement="top" title="Delete FW" onclick="deleteFw('${item.fw_name}')">Delete</button>
                                </div>
                            </div>
                        </td>    
                    </tr>
                `);
            })
            $(".deleteFwBtn").hide();
            if (response.dirArray.length == 0) {
                $("#fwdata").append(`
                   <tr><td colspan="5" class="text-center ">No Record</td></tr>
                `);
            }
            else{
                $("#fwdata tr td:nth-child(1)").css("width", "8%");
                $("#fwdata tr td:nth-child(2)").css("width", "20%");
                $("#fwdata tr td:nth-child(3)").css("width", "25%");
                $("#fwdata tr td:nth-child(4)").css("width", "25%");
                $("#fwdata tr td:nth-child(5)").css("width", "13%");
            }
            
            $("#factoryData").empty();

            response.factoryArray.map((item, index) => {
                $("#factoryData").append(`
                    <tr>
                        <td>${moment.utc(item.last_activated, "YYYY-MM-DD HH:mm:ss").local().format("MMMM DD, YYYY HH:mm:ss")}</td>   
                    </tr>
                `);
            })

            if (response.factoryArray.length == 0) {
                $("#factoryData").append(`
                   <tr><td colspan="1" class="text-center ">No Record</td></tr>
                `);
            }
        },
        error: function (ex) {
            console.log(ex);
        }
    });
}

function deleteFw(selectedFwName) {
    if (!selectedFwName) {
        swal("Please select a firmware to delete");
    } else {
        hardwareAdminOperations("delete", selectedFwName);
    }
}

$("#btnFactoryReset").click(function () {
    hardwareAdminOperations("factoryReset");
});