var fileId = 0;
var uploadType = parent.uploadType;
var fw_name;
var selectedUploadType = "";

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


function Request() {
    var request = {
        url: "",
        parameters: {},
        Type: ""
    };
    return request;
}
function CallPythonService(request) {
	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, response);
        },
        error: function (ex) {
            if(!parent.isProduction){
				console.log(ex);
			}
        }
    });
}
function BindResponseData(Type, response) { 
	if(Type == 'hardwareAdminOperations')
	{   
        $("#spinner").hide(); 
       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 () {
    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 () {

    $('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 $('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") {
		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);
				} else {
				  	parent.swal("Cancelled", "", "error");
				}
		});
	}
}
ReadDir()
$(document).on('click', 'input[name="fw_name"]', function () {
    // Hide all buttons
    $(".button-cell").hide();

    // Show the button in the clicked row
    $(this).closest('tr').find('.button-cell').show();
});

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) {
            response.dirArray.map((item,index) => {
                $("#fwdata").append(`
                    <tr>
                        <!-- <td><input type="radio" value="${item.fw_name} id="radio_${index}" name="fw_name"></td> -->   
                        <td>${moment(item.uploaded_date).format("DD, MMMM YYYY")}</td>   
                        <td>${item.fw_name}</td>   
                        <td class="button-cell">
                            ${item.status != "True" ?`<button class="btn btn-primary" style="width : 100px" onclick="hardwareAdminOperations('activate','${item.fw_name}')" data-toggle="tooltip" data-placement="top" title="Activate">Activate</button>` :  `<button class='btn btn-warning disabled' style="cursor:not-allowed;width : 100px;" disabled>Activated</button>`}    
                        </td>    
                    </tr>
                `);
            })
            if(response.dirArray.length == 0){
                $("#fwdata").append(`
                   <tr><td colspan="3" class="text-center ">No Record</td></tr>
                `);
            }
            // $('#table').DataTable({
            //     searching : false
            // })
        },
        error: function (ex) {
            console.log(ex);
        }
    });
}