$(function(){
    $('#inpSearchPage').on('keyup', function(){
        searchPages();
    });

    loadPages();
});

function searchPages(){
    let value = $('#inpSearchPage').val().toLowerCase();

    $(".div-page").each(function(i, e) {
        let pageText = $(e).find('small').text().toLowerCase();
        if (pageText.indexOf(value) < 0){
            $(e).hide();
        } else {
            $(e).show();
        }
    });
}

function loadPages(){
    $.blockUI();
    $.ajax({
        type: "GET",
        url: "/Pages/Index/?handler=Pages",
        data: {
        },
        success: function (data) {
            if (data.successful){
                let pageContent = $('.div-pages');
                pageContent.empty();

                if (data.pages){
                    data.pages.forEach((page) => {
                        addPageToDiv(page);
                    });
                }
            } else {
                Swal.fire('Napaka', data.error, 'error');
                console.log(data);
            }
            $.unblockUI();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr);
            alert(xhr.responseText);
            $.unblockUI();
        }
    });
}

function addPageToDiv(page){
    let date = new Date();
    let preview;
    if (page.type == 3){
        preview = `<div class='img-link'><i class="fas fa-link fa-5x"></i></div>`;
    } else {
        preview = `<img class="img-thumbnail rounded" src="/bulletin-board-images/pages/${page.image}?${date.getTime()}" onerror="this.src='/img/imgNotExists.jpg'" alt="page image" />`
    }
    let element = $(`<div class="div-page" data-id="${page.idBulletinBoardPage}">
    ${preview}
    <small>${page.name}</small>
    <div class="tools">
        <a href="javascript:;" class="btn btn-xs icon-btn btn-outline-primary borderless" onclick="pageOpenEditor(this);" data-toggle="tooltip" data-placement="top" title="Urejevalnik" data-state="secondary"><i class="far fa-edit"></i></a>
        <a href="javascript:;" class="btn btn-xs icon-btn btn-outline-secondary borderless" onclick="openModalEditPage(this);" data-toggle="tooltip" data-placement="top" title="Urejanje" data-state="secondary"><i class="fas fa-pencil-alt"></i></a>
        <a href="javascript:;" class="btn btn-xs icon-btn btn-outline-danger borderless" onclick="deletePage(this)"><i class="fas fa-trash-alt"></i></a>
    </div>
</div>`);
    $('.div-pages').append(element);

    element.find('[data-toggle="tooltip"]').tooltip();
}

function openModalAddPage(){
    $('#inpModalAddEditPageIdPage').val(0);
    $('#inpModalAddEditPageName').val('');
    $('#divModalAddEditPage').modal('show');
}

function openModalEditPage(el){
    let idBulletinBoardPage = parseInt($(el).parent().parent().attr('data-id'));
    if (isNaN(idBulletinBoardPage)){
        Swal.fire('Napaka ni id strani!', '', 'error');
        return;
    }
    $.blockUI();
    $.ajax({
        type: "GET",
        url: "/Pages/Index/?handler=Page",
        data: {
            id: idBulletinBoardPage
        },
        success: function (data) {
            if (data.successful){
                $('#inpModalAddEditPageIdPage').val(data.page.idBulletinBoardPage);
                $('#inpModalAddEditPageName').val(data.page.name);
                $('#selModalAddEditPageRatio').val(data.page.ratio).trigger('change');
                $('#selModalAddEditPageType').val(data.page.type).trigger('change');
                $('#divModalAddEditPage').modal('show');
            } else {
                Swal.fire('Napaka', data.error, 'error');
                console.log(data);
            }
            $.unblockUI();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr);
            alert(xhr.responseText);
            $.unblockUI();
        }
    });
}

function saveModalAddEditPage(){
    let name = $('#inpModalAddEditPageName').val();
    let ratio = parseInt($('#selModalAddEditPageRatio').val());
    let type = parseInt($('#selModalAddEditPageType').val());
    let idBulletinBoardPage = parseInt($('#inpModalAddEditPageIdPage').val());
    if (name === ''){
        Swal.fire('Ime ni vneseno', '', 'warning');
        return;
    }

    if (isNaN(ratio)){
        Swal.fire('Razmerje ni vneseno', '', 'warning');
        return;
    }

    if (isNaN(type)){
        Swal.fire('Tip ni vnesen', '', 'warning');
        return;
    }

    $.blockUI();
    $.ajax({
        type: "POST",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        url: "/Pages/Index/?handler=BoardPage",
        data: { page : {
            idBulletinBoardPage,
            name,
            ratio,
            type
        }},
        success: function(data) {
            if (data.successful){
                if (idBulletinBoardPage <= 0){
                    //Ce je nova dodam in odprem editor
                    addPageToDiv(data.page);
                    openEditor(data.page.idBulletinBoardPage);
                }
                $('#divModalAddEditPage').modal('hide');
            } else {
                Swal.fire('Napaka', data.error, 'error');
                console.log(data);
            }
            $.unblockUI();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.responseText);
            $.unblockUI();
        }
    });
}

function pageOpenEditor(el){
    openEditor(parseInt($(el).parent().parent().attr('data-id')));
}

function openEditor(id){
    $.blockUI();
    $.ajax({
        type: "GET",
        url: "/Pages/Index/?handler=Page",
        data: {
            id
        },
        success: function (data) {
            if (data.successful){
                switch (data.page.type){
                    case 1: //Editor notes
                        window.location.href = "/Pages/EditMain?idPage=" + data.page.idBulletinBoardPage;
                        break;
                    case 2: //Picture
                        $('#inpModalPageEditorPictureIdPage').val(data.page.idBulletinBoardPage);
                        $('#imgModalPageEditorPicture').attr("src","/bulletin-board-images/pages/" + data.page.image);
                        $('#divModalPageEditorPicture').modal('show');
                        break;
                    case 3: //Link
                        $('#inpModalPageEditorLinkIdPage').val(data.page.idBulletinBoardPage);
                        $('#inpModalPageEditorLinkLink').val(data.page.externalLink);
                        $('#divModalPageEditorLink').modal('show');
                        break;
                }
            } else {
                Swal.fire('Napaka', data.error, 'error');
                console.log(data);
            }
            $.unblockUI();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr);
            alert(xhr.responseText);
            $.unblockUI();
        }
    });
}

function saveModalPageEditorLink(){
    let link = $('#inpModalPageEditorLinkLink').val();
    let idPage = parseInt($('#inpModalPageEditorLinkIdPage').val());

    $.blockUI();
    $.ajax({
        type: "POST",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        url: "/Pages/Index/?handler=BoardPageLink",
        data: { idPage, link},
        success: function(data) {
            if (data.successful){
                $('#divModalPageEditorLink').modal('hide');
            } else {
                Swal.fire('Napaka', data.error, 'error');
                console.log(data);
            }
            $.unblockUI();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.responseText);
            $.unblockUI();
        }
    });
}

function saveModalPageEditorPicture(){
    let idPage = parseInt($('#inpModalPageEditorPictureIdPage').val());

    let files = $('#inpModalPageEditorPicturePicture').prop("files"); 
	let formData = new FormData();
	formData.append("file", files[0]);
	formData.append("idPage", idPage);

    $.blockUI();
    $.ajax({
        type: "POST",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        url: "/Pages/Index/?handler=BoardPagePicture",
        data: formData,
        cache: false,
		contentType: false,
		processData: false,
        success: function(data) {
            if (data.successful){
                let date = new Date();
                $('.div-page[data-id="' + idPage + '"] > img').attr('src', '/bulletin-board-images/pages/' + data.page.image + '?' + date.getTime());
                $('#divModalPageEditorPicture').modal('hide');
                $.unblockUI();
            } else {
                Swal.fire('Napaka', data.error, 'error');
                console.log(data);
            }
            $.unblockUI();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.responseText);
            $.unblockUI();
        }
    });
}

function deletePage(el){
    let idPage = parseInt($(el).parent().parent().attr('data-id'));
    $.blockUI();
    $.ajax({
        type: "DELETE",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        url: "/Pages/Index/?handler=BoardPage",
        data: { 
            idPage
        },
        success: function(data) {
            if (data.successful){
                $(el).parent().parent().remove();
            } else {
                Swal.fire('Napaka', data.error, 'error');
                console.log(data);
            }
            $.unblockUI();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.responseText);
            $.unblockUI();
        }
    });
}