$(function () {
    $('.div-note-edit-color>div').on('click', function(){
        $('.div-note-edit-color>div').removeClass('active');
        $(this).addClass('active');
    });

});


let divCanvas;
let canWidth;
let canHeight;
let notes = [];

function addNewNote(){
    let idPage = parseInt($('#inpSelectedBoardPageId').val());
    if (isNaN(idPage) || idPage <= 0){
        Swal.fire('Stran ni izbrana', '', 'warning');
        return;
    }
    let tmpId = -1;
    let tmpZindex = 50;
    notes.forEach(note => {
        if (note.id <= tmpId){
            tmpId = note.id -1;
        }

        if (note.zindex >= tmpZindex){
            tmpZindex = note.zindex + 1;
        }
    });
    let note = new Note(tmpId, divCanvas, 0, 0, 400, 240, 'Vnesi besedilo', 'note-color-white', tmpZindex);
    notes.push(note);
    note.refresh();
}

function noteChangeZindex(id, front){
    let note = getNote(id);
    let maxIndex = 0;
    let minIndex = 999999999999;
    notes.forEach(tmpNote => {
        if (tmpNote.zindex > maxIndex){
            maxIndex = tmpNote.zindex;
        }

        if (tmpNote.zindex < minIndex){
            minIndex = tmpNote.zindex;
        }
    });
    if (front){
        //ce je isti ga potem ne premikam
        if (note.zindex != maxIndex){
            note.zindex = maxIndex + 1;
        }
    } else {
        if (note.zindex != minIndex){
            note.zindex = minIndex - 1;
        }
    }
    note.refresh();
}

function deleteNote(id){
    let note = getNote(id);
    note.element.remove();
    let newArray = [];

    notes.forEach(tmpNote => {
        if (tmpNote.id != note.id){
            newArray.push(tmpNote);
        }
    });
    notes = newArray;
}

function openModalEditNote(id){
    $('#inpModalEditNoteIdNote').val(id);
    note = getNote(id);

    $('#divModalEditNote').modal('show');
    $('#divModalEditNoteSummernote').summernote('destroy');
    $('#divModalEditNoteSummernote').html(note.content);
    $('#divModalEditNoteSummernote').summernote({height: 400,});
    $('.div-note-edit-color>div').removeClass('active');
    $('.div-note-edit-color>.' + note.colorClass).addClass('active');
}

function saveModalEditNote(){
    let idNote = parseInt($('#inpModalEditNoteIdNote').val());
    note = getNote(idNote);
    note.content = $('#divModalEditNoteSummernote').summernote('code');
    note.colorClass = $('.div-note-edit-color>.active').attr('class').replace(' active', '');
    note.refresh();
    $('#divModalEditNote').modal('hide');
}

function getNote(id){
    let note;
    notes.forEach(e => {
        if (e.id === id){
            note = e;
        }
    });
    return note;
}

function svgTest(){
    var node = document.getElementById('divCanvas');

    htmlToImage.toSvg(node)
    .then(function (dataUrl) {
        console.log(dataUrl);
        var link = document.createElement('a');
        link.href = dataUrl;
        link.download = 'Download.jpg';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        return;
        var img = new Image();
        img.src = dataUrl;
        document.body.appendChild(img);
    })
    .catch(function (error) {
        console.error('oops, something went wrong!', error);
    });
}

function openModalSelectBoard() {
    $.blockUI();
    $.ajax({
        type: "GET",
        url: "/Editor/EditMain/?handler=Boards",
        data: {
        },
        success: function (data) {
            if (data.successful){
                let tmp = '';
                data.boards.forEach(element => {
                    tmp += `<tr data-id='${element.idBulletinBoard}' onclick='modalSelectBoardSelect(this);'>`;
                    tmp += '<td>' + element.name + '</td>';
                    tmp += '</tr>';
                });
                $('#tbodyModalSelectBoard').html(tmp);
                $('#divModalSelectBoard').modal('show');
            } else {
                console.log(data);
                alert(data);
            }
            $.unblockUI();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr);
            alert(xhr.responseText);
            $.unblockUI();
        }
    });
}

function modalSelectBoardSelect(element){
    loadBoard(parseInt($(element).attr('data-id')));
    $('#divModalSelectBoard').modal('hide');
}

function loadBoard(id){
    $.blockUI();
    $.ajax({
        type: "GET",
        url: "/Editor/EditMain/?handler=Board",
        data: {
            id
        },
        success: function (data) {
            if (data.successful){
                $('.div-board>h5').text(data.board.name);
                $('.div-board').attr('data-idboard', data.board.idBulletinBoard);
                let placeholder = $('#divPlaceholder');
                placeholder.empty();
                let tmpSplit = data.board.ratioString.split(':');
                canWidth = placeholder.width();
                canHeight = canWidth / (parseFloat(tmpSplit[0]) / parseFloat(tmpSplit[1]));
                divCanvas = $(`<div id='divCanvas'></div>`);
                placeholder.append(divCanvas);
                divCanvas.css({
                    'width': '100%',
                    'height': canHeight + 'px',
                    'background-color': 'white',
                    'padding': '5px'
                });
                $('[data-idpage]').remove();
                if (data.board.pages){
                    data.board.pages.forEach(element => {
                        boardAddPage(element);
                    });
                }
            } else {
                Swal.fire('Napaka', data.error, 'error');
                console.log(data);
            }
            $.unblockUI();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr);
            alert(xhr.responseText);
            $.unblockUI();
        }
    });
}

function openModalBoardAddNewPage(){
    let idBulletinBoard = parseInt($('.div-board').attr('data-idboard'));
    if (isNaN(idBulletinBoard) || idBulletinBoard <= 0){
        Swal.fire('Oglasna deska ni izbrana', '', 'warning');
        return;
    }

    $('#titleModalAddEditPage').html('Dodaj list');
    $('#inpModalAddEditPageName').val('');
    $('#inpModalAddEditPageId').val(0);
    $('#inpModalAddEditPageDuration').val('30');
    $('#divModalAddEditPage').modal('show');
}

function openModalBoardEditPage(id){
    $('#titleModalAddEditPage').html('Uredi list');
    $.blockUI();
    $.ajax({
        type: "GET",
        url: "/Editor/EditMain/?handler=Page",
        data: {
            id
        },
        success: function (data) {
            if (data.successful){
                $('#inpModalAddEditPageId').val(data.page.idBulletinBoardPage);
                $('#inpModalAddEditPageName').val(data.page.name);
                $('#inpModalAddEditPageDuration').val(data.page.duration);
                $('#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 boardAddNewPageSave(){
    let idBulletinBoardPage = parseInt($('#inpModalAddEditPageId').val());
    let name = $('#inpModalAddEditPageName').val();
    let duration = parseInt($('#inpModalAddEditPageDuration').val());
    let idBulletinBoard = parseInt($('.div-board').attr('data-idboard'));
    if (name === ''){
        Swal.fire('Ime ni vneseno', '', 'warning');
        return;
    }

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

    if (duration < 1 || duration > 2147483640){
        Swal.fire('Trajanje mora biti med 1 in 2147483640', '', 'warning');
        return;
    }

    if (isNaN(idBulletinBoard) || idBulletinBoard <= 0){
        Swal.fire('Oglasna deska ni izbrana', '', 'warning');
        return;
    }

    $.blockUI();
    $.ajax({
        type: "POST",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        url: "EditMain/?handler=BoardPage",
        data: { page : {
            name,
            duration,
            idBulletinBoard,
            idBulletinBoardPage
        } },
        success: function(data) {
            if (data.successful){
                if (idBulletinBoardPage <= 0){
                    boardAddPage(data.page);
                } else {
                    let currentPage = $('[data-idpage="' + idBulletinBoardPage + '"]');
                    let elAfter = currentPage.next();
                    currentPage.remove();
                    boardAddPage(data.page, elAfter);
                }
                selectPage(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 boardAddPage(page, elAfter){
    let element = $(`<div class='div-page' data-idpage='${page.idBulletinBoardPage}'>
    <h5>${page.name}</h5>
    <small>${page.duration} sekund</small>
</div>`);
    if (elAfter){
        element.insertBefore(elAfter);
    } else {
        element.insertBefore(".add-page");
    }
    element.on('click', function (){
        let id = parseInt($(this).attr('data-idpage'));
        selectPage(id);
    });
    element.on('dblclick', function (){
        let id = parseInt($(this).attr('data-idpage'));
        openModalBoardEditPage(id);
    });
}

function selectPage(id){
    $.blockUI();
    $.ajax({
        type: "GET",
        url: "/Editor/EditMain/?handler=Page",
        data: {
            id
        },
        success: function (data) {
            if (data.successful){
                $('[data-idpage]').removeClass('page-active');
                $('[data-idpage="' + id + '"]').addClass('page-active');
                $('#inpSelectedBoardPageId').val(id);
                notes = [];
                $('.div-note').remove();
                if (data.page.notes){
                    data.page.notes.forEach(el => {
                        let note = new Note(el.idNote, divCanvas, el.x, el.y, el.width, el.height, el.content, el.colorClass, el.zindex);
                        notes.push(note);
                        note.refresh();
                    });
                }
            } else {
                Swal.fire('Napaka', data.error, 'error');
                console.log(data);
            }
            $.unblockUI();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr);
            alert(xhr.responseText);
            $.unblockUI();
        }
    });
}

function saveNotes(){
    let idBulletinBoardPage = parseInt($('#inpSelectedBoardPageId').val());
    if (isNaN(idBulletinBoardPage) || idBulletinBoardPage <= 0){
        Swal.fire('Stran ni izbrana', '', 'warning');
        return;
    }
    let array = [];

    notes.forEach(note => {
        array.push({
            idNote: note.id,
            idBulletinBoardPage,
            x: note.x,
            y: note.y,
            width: note.width,
            height: note.height,
            content: note.content,
            colorClass: note.colorClass,
            zindex: note.zindex
        })
    });

    $.blockUI();
    $.ajax({
        type: "POST",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        url: "EditMain/?handler=Notes",
        data: { 
            idBulletinBoardPage,
            notes: array
        },
        success: function(data) {
            if (data.successful){
                selectPage(idBulletinBoardPage);
            } else {
                Swal.fire('Napaka', data.error, 'error');
                console.log(data);
            }
            $.unblockUI();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.responseText);
            $.unblockUI();
        }
    });
}



