$(function(){
    $('#inpSearchBoard').on('keyup', function(){
        searchBoards();
    });

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

    loadBoards();
});

function searchBoards(){
    let value = $('#inpSearchBoard').val().toLowerCase();

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

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

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

function loadBoards(){
    $.blockUI();
    $.ajax({
        type: "GET",
        url: "/BoardsLinks/Index/?handler=Boards",
        data: {
        },
        success: function (data) {
            if (data.successful){
                let boardContent = $('.boards-content');
                boardContent.empty();

                if (data.boards){
                    data.boards.forEach((board) => {
                        console.log(board);
                        boardContent.append(`<div class="div-board">
                        <h5>${board.name}</h5>
                    </div>
                    <div class="div-pages" ondrop="dropPage(event, this)" ondragover="allowDropPage(event, this)" data-idboard="${board.idBulletinBoard}">
                        
                    </div>
                    <hr/>`);
                        if (board.links){
                            board.links.forEach((link) => {
                                addPageToBoard(board.idBulletinBoard, link);
                            });
                        }
                    });
                }
                
            } else {
                Swal.fire('Napaka', data.error, 'error');
                console.log(data);
            }
            $.unblockUI();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr);
            alert(xhr.responseText);
            $.unblockUI();
        }
    });
}

function allowDropPage(ev) {
    ev.preventDefault();

    // if (ev.dataTransfer.getData("idPage")){
    //     ev.preventDefault();
    // }
}
  
function dragPage(ev, el) {
    $('.available-page[data-dragg="1"]').removeAttr('data-dragg');
    $(el).attr('data-dragg', '1');
}
  
function dropPage(ev, el) {
    ev.preventDefault();
    let idPage = parseInt($('.available-page[data-dragg="1"]').attr('data-id'));
    if (isNaN(idPage)){
        return;
    }
    $('.available-page[data-dragg="1"]').removeAttr('data-dragg');
    let idBoard = parseInt($(el).attr('data-idboard'));
    insertPageToBoard(idBoard, idPage);
}

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

function addPageToAllBoards(el){
    let idPage = parseInt($(el).parent().parent().attr('data-id'));

    $('.div-pages').each(function (i, e){
        let idBoard = parseInt($(e).attr('data-idboard'));
        insertPageToBoard(idBoard, idPage);
    });
}

function addPageToBoard(idBoard, link){
    let div = $('.div-pages[data-idboard="' + idBoard +  '"]');

    let preview;
    if (link.bulletinBoardPage.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/${link.bulletinBoardPage.image}" onerror="this.src='/img/imgNotExists.jpg'" alt="page image" />`
    }

    div.append(`<div class="div-page" data-id="${link.idLink}" data-idPage='${link.bulletinBoardPage.idBulletinBoardPage}' data-duration='${link.duration}'>
    ${preview}
    <small>${link.bulletinBoardPage.name}</small>
    <div class="tools">
        <a href="javascript:;" class="btn btn-xs icon-btn btn-outline-primary borderless" onclick="moveLink(this, -1)"><i class="fas fa-chevron-left"></i></a>
        <a href="javascript:;" class="btn btn-xs icon-btn btn-outline-secondary borderless" onclick="setDuration(this)"><i class="far fa-clock"></i></a>
        <a href="javascript:;" class="btn btn-xs icon-btn btn-outline-danger borderless" onclick="deleteLink(this)"><i class="fas fa-trash-alt"></i></a>
        <a href="javascript:;" class="btn btn-xs icon-btn btn-outline-primary borderless" onclick="moveLink(this, 1)"><i class="fas fa-chevron-right"></i></a>
    </div>
</div>`);
}

function deleteLink(el){
    let idLink = parseInt($(el).parent().parent().attr('data-id'));
    if (isNaN(idLink)){
        return;
    }

    $.blockUI();
    $.ajax({
        type: "DELETE",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        url: "/BoardsLinks/Index/?handler=Link",
        data: { 
            idLink
        },
        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) {
            console.log({xhr, ajaxOptions, thrownError});
            alert(xhr.responseText);
            $.unblockUI();
        }
    });   
}

function moveLink(el, direction){
    let divStart = $(el).parent().parent();
    let idLinkStart = parseInt(divStart.attr('data-id'));
    if (isNaN(idLinkStart)){
        return;
    }

    let divEnd;
    let idLinkEnd;
    if (direction == -1){
        divEnd = divStart.prev();
    } else {
        divEnd = divStart.next();
    }

    idLinkEnd = parseInt(divEnd.attr('data-id'));

    if (isNaN(idLinkEnd)){
        return;
    }

    $.blockUI();
    $.ajax({
        type: "POST",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        url: "/BoardsLinks/Index/?handler=SwapLinkOrder",
        data: { 
            idLinkStart,
            idLinkEnd
        },
        success: function(data) {
            if (data.successful){
                if (direction == -1){
                    divStart.insertBefore(divEnd);
                } else {
                    divStart.insertAfter(divEnd);
                }
            } else {
                Swal.fire('Napaka', data.error, 'error');
                console.log(data);
            }
            $.unblockUI();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log({xhr, ajaxOptions, thrownError});
            alert(xhr.responseText);
            $.unblockUI();
        }
    });   
}

function setDuration(el){
    let div = $(el).parent().parent();
    let idLink = parseInt(div.attr('data-id'));
    if (isNaN(idLink)){
        return;
    }
    let step = 5;
    let duration = div.attr('data-duration');
    Swal.fire({
        title: 'Trajanje [s]',
        html: `
          <input
            type="number"
            value="${duration}"
            step="${step}"
            class="swal2-input"
            id="range-value">`,
        input: 'range',
        inputValue: duration,
        inputAttributes: {
          min: '5',
          max: '3600',
          step: step.toString(),
        },
        confirmButtonText: 'Potrdi',
        cancelButtonText: 'Prekliči',
        showCancelButton: true,
        didOpen: () => {
          const inputRange = Swal.getInput();
          const inputNumber = Swal.getPopup().querySelector('#range-value');
      
          // remove default output
          Swal.getPopup().querySelector('output').style.display = 'none'
          inputRange.style.width = '100%'
      
          // sync input[type=number] with input[type=range]
          inputRange.addEventListener('input', () => {
            inputNumber.value = inputRange.value
          })
      
          // sync input[type=range] with input[type=number]
          inputNumber.addEventListener('change', () => {
            inputRange.value = inputNumber.value
          })
        },
      }).then((result) => {
        console.log(result);
        if (result.isConfirmed) {
            let newDuration = parseInt(result.value);
            $.blockUI();
            $.ajax({
                type: "POST",
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
                },
                url: "/BoardsLinks/Index/?handler=LinkDuration",
                data: { 
                    idLink,
                    duration: newDuration
                },
                success: function(data) {
                    if (data.successful){
                        div.attr('data-duration', data.link.duration);
                    } else {
                        Swal.fire('Napaka', data.error, 'error');
                        console.log(data);
                    }
                    $.unblockUI();
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console.log({xhr, ajaxOptions, thrownError});
                    alert(xhr.responseText);
                    $.unblockUI();
                }
            });  
        }
      });
}