var folderHistory = false;
var path = '';
var currentFolder = '';
var folderGoBack = [];
var permissionModalHtml = null;
var progressBar = 0;
var originalFolder;
var mode = '';
function init(folder,pmode = '')
{
    mode = pmode;
    console.log(mode);
    originalFolder = folder;
    loadFolder(folder);
    loadHistory();
}

function loadHistory() {
    updateProgressBar(progressBar+5);
    let btnBack = $('#backbtn');
    btnBack.prop('disabled','true');
    $.ajax({
        type: 'GET',
        url: '/api/drive/patharray?api_token=' + api_token,
        success: function (rawpath) {
            updateProgressBar(progressBar+30);
            var path = JSON.parse(rawpath);
            Object.keys(path).forEach(function (item) {
                var dir = path[item].dirname.split('/');
                folderGoBack[path[item].basename] = dir[dir.length - 1];
            });
            folderHistory = true;
            updateProgressBar(progressBar+10);
            if(!currentFolder == '' || !currentFolder == 'root')
            {
                if (mode == 'folder')
                {
                    if (currentFolder != originalFolder)
                    {
                        btnBack.removeAttr('disabled');
                    }
                }
                else
                {
                    btnBack.removeAttr('disabled');
                }
            }
            updateProgressBar(progressBar+5);
        },
        error: function () {
            if (folderHistory)
            {
                showNotification('error', 'Impossible de charger la hiérachie des dossiers', 'top', 'center')
            }
        }
    });
}

function loadFolder(folder) {
    if (folder != undefined)
    {
        showLoader();
        updateProgressBar(progressBar+5);
        $.ajax({
            type: 'GET',
            url: '/api/drive/folders/'+folder+'?api_token=' + api_token,
            success: function (template) {
                updateProgressBar(progressBar+30);
                $(".drive-explorer").html(template);
                currentFolder = folder;
                if (mode != 'folder')
                {
                    window.history.pushState("object or string", "Page Title", "/admin/drive/"+folder);
                }
                updateProgressBar(progressBar+5);
                hideLoader();

                $('.currentDir').attr('value',folder);

                if (folderHistory)
                {
                    if((currentFolder == '' || currentFolder == 'root'))
                    {
                        $('#backbtn').prop('disabled','true');
                    }
                    else
                    {
                        if (mode == 'folder')
                        {
                            if (currentFolder != originalFolder)
                            {
                                $('#backbtn').removeAttr('disabled');
                            }
                            else
                            {
                                $('#backbtn').prop('disabled','true');
                            }
                        }
                        else
                        {
                            $('#backbtn').removeAttr('disabled');
                        }
                    }
                }
                updateProgressBar(progressBar+10);
            },
            error: function () {
                showNotification('error', 'Impossible de charger le dossier '+folder, 'top', 'center')
            }
        });
    }
}
function goBack()
{
    loadFolder(folderGoBack[currentFolder]);
}

function showfile(file) {
    var fa = $('#fa-'+file);
    if(!fa.hasClass('fa-flip-vertical'))
    {
        $('#'+file).removeClass('d-none');
        fa.addClass('fa-flip-vertical');
    }
    else
    {
        $('#'+file).addClass('d-none');
        fa.removeClass('fa-flip-vertical');
    }
}

function showLoader() {
    $('#loader').fadeIn(200);
}

function hideLoader() {
    $('#loader').fadeOut(650);
}

function deleteFile(file, folder)
{
    swal({
        title: 'Êtes vous certain de vouloir supprimer le fichier ?',
        text: "Vous ne pourrez pas annuler cette action",
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Oui',
        cancelButtonText: 'Non'
    }).then((result) => {
        if (result.value) {
            window.location.href = '/file/delete?f='+file+'&d='+folder
        }
    })
}

function deleteFolder(folder)
{
    swal({
        title: 'Êtes vous certain de vouloir supprimer le dossier ?',
        text: "Vous ne pourrez pas annuler cette action",
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Oui',
        cancelButtonText: 'Non'
    }).then((result) => {
        if (result.value) {
            window.location.href = '/folder/delete?d='+folder
        }
    })
}

function refreshFolder() {
    loadFolder(currentFolder);
}

function editPermission(folder,subject,id)
{
    $('#permissionModal').on('hidden.bs.modal', function (e) {
        $('#permissionModalHtml').html(permissionModalHtml);
    });
    let csrf = $('input[name="_token"]').val();
    $.ajax({
        type: 'GET',
        url: '/api/drive/'+folder+'/permission/'+subject+'/'+id+'?api_token=' + api_token,
        success: function (modal) {
            permissionModalHtml = $('#permissionModalHtml').html();
            $('#permissionModalHtml').html(modal);

            $('#csrf').val(csrf);

            $('#permissionModal').modal('show');
        },
        error: function () {
            showNotification('error', 'Impossible de charger le dossier '+folder, 'top', 'center')
        }
    });
}

function addPermission(folder,subject)
{
    $('#permissionModal').on('hidden.bs.modal', function (e) {
        $('#permissionModalHtml').html(permissionModalHtml);
    });
    let csrf = $('input[name="_token"]').val();
    $.ajax({
        type: 'GET',
        url: '/api/drive/'+folder+'/addpermission/'+subject+'/?api_token=' + api_token,
        success: function (modal) {
            permissionModalHtml = $('#permissionModalHtml').html();
            $('#permissionModalHtml').html(modal);

            $('#csrf').val(csrf);

            $('#permissionModal').modal('show');
        },
        error: function () {
            showNotification('error', 'Impossible de charger le dossier '+folder, 'top', 'center')
        }
    });
}

function deletePermission(folder,subject,id)
{
    $('#permissionModal').on('hidden.bs.modal', function (e) {
        $('#permissionModalHtml').html(permissionModalHtml);
    });
    swal({
        title: 'Êtes vous certain de vouloir supprimer les permissions ?',
        text: "Vous ne pourrez pas annuler cette action",
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Oui',
        cancelButtonText: 'Non'
    }).then((result) => {
        if (result.value) {
            window.location.href = '/admin/drive/'+folder+'/deletepermission/'+subject+'/'+id;
        }
    })

}

function updateProgressBar(value)
{
    progressBar = value;
    let bar = $('#progress-bar');
    bar.css('width',value+"%");
    if (progressBar >= 100)
    {
        $('.progress').fadeOut(1500);
    }
    else
    {
        $('.progress').fadeIn(650);
    }
}

function updateHeader(perm)
{
    if (perm == 1)
    {
        $('#createDropdown').removeClass('d-none');
        $('#uploadDropdown').removeClass('d-none');
    }
    else
    {
        $('#createDropdown').addClass('d-none');
        $('#uploadDropdown').addClass('d-none');
    }
}
