$(function () {
    $('.div-note-edit-color>div').on('click', function(){
        $('.div-note-edit-color>div').removeClass('active');
        $(this).addClass('active');
    });
    $(document).on('keyup', function(e){
        if (e.originalEvent.key === 'Delete' || e.originalEvent.key === 'Backspace'){
            let id = parseInt($('.div-note.active').attr('data-id'));
            if (isNaN(id)){
                return;
            }
            deleteNote(id);
        }
    });
    
    loadPage();
});


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

function addNewNote(){
    let idPage = parseInt($('#inpIdPage').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 loadBoard(id){
    $.blockUI();
    $.ajax({
        type: "GET",
        url: "/Pages/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);
                
                $('[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 loadPage(){
    let id = parseInt($('#inpIdPage').val());
    $.blockUI();
    $.ajax({
        type: "GET",
        url: "/Pages/EditMain/?handler=Page",
        data: {
            id
        },
        success: function (data) {
            if (data.successful){
                let placeholder = $('#divPlaceholder');
                placeholder.empty();
                let tmpSplit = data.page.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'
                });
                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($('#inpIdPage').val());
    if (isNaN(idBulletinBoardPage) || idBulletinBoardPage <= 0){
        Swal.fire('Stran ni izbrana', '', 'warning');
        return;
    }
    //skrijemo okvirje
    $('.div-note.active').removeClass('active');

    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){
                savePageImage();
            } else {
                Swal.fire('Napaka', data.error, 'error');
                console.log(data);
            }
            $.unblockUI();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.responseText);
            $.unblockUI();
        }
    });
}

function savePageImage(){
    let idPage = parseInt($('#inpIdPage').val());
    if (isNaN(idPage) || idPage <= 0){
        Swal.fire('Stran ni izbrana', '', 'warning');
        return;
    }

    $.blockUI();

    var node = document.getElementById('divCanvas');
    htmlToImage.toSvg(node)
    .then(function (base64String) {
        fetch(base64String)
        .then(res => res.blob())
        .then(blob => {
            let formData = new FormData();
            formData.append("file", blob);
            formData.append("idPage", idPage);
            $.ajax({
                type: "POST",
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
                },
                url: "/Pages/EditMain/?handler=BoardPageImage",
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function(data) {
                    if (data.successful){
                        loadPage(idPage);
                    } else {
                        Swal.fire('Napaka', data.error, 'error');
                        console.log(data);
                    }
                    $.unblockUI();
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.responseText);
                    $.unblockUI();
                }
            });
        });
    })
    .catch(function (error) {
        $.unblockUI();
        console.error('oops, something went wrong!', error);
    });
}

function selectNote(id){
    $('.div-note.active').removeClass('active');
    $('.div-note[data-id="' + id + '"]').addClass('active');

}


