$(function () {
});


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


function loadNotes(){
    let note = new Note(1, divCanvas, 200, 0, 400, 240, '<h3>Naslov</h3><hr/><p>Test</p>' );

    notes.push(note);

    let note2 = new Note(2, divCanvas, 0, 0, 400, 240);
    notes.push(note2);

    notes.forEach(note => {
        note.refresh();
    });
}

function addNewNote(){
    let tmpId = -1;
    notes.forEach(note => {
        if (note.id <= tmpId){
            tmpId = note.id -1;
        }
    });
    let note = new Note(tmpId, divCanvas, 0, 0, 400, 240, 'Vnesi besedilo');
    notes.push(note);
    note.refresh();
}

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

    $('#divModalEditNote').modal('show');
    $('#divModalEditNoteSummernote').summernote('destroy');
    $('#divModalEditNoteSummernote').html(note.content);
    $('#divModalEditNoteSummernote').summernote({height: 400,});
}

function saveModalEditNote(){
    let idNote = parseInt($('#inpModalEditNoteIdNote').val());
    note = getNote(idNote);
    note.content = $('#divModalEditNoteSummernote').summernote('code');
    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) {
        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){
                $('#lblBoardName').text(data.board.name);
                $('#lblBoardName').attr('data-idboard', data.board.idBulletinBoard);
                let placeholder = $('#divPlaceholder');
                placeholder.empty();
                console.log(data);
                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 {
                console.log(data);
                alert(data); //TODO swal
            }
            $.unblockUI();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr);
            alert(xhr.responseText);
            $.unblockUI();
        }
    });
}

function openModalBoardAddNewPage(){
    $('#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 {
                console.log(data);
                alert(data); //TODO swal
            }
            $.unblockUI();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr);
            alert(xhr.responseText);
            $.unblockUI();
        }
    });
}

function boardAddNewPage(){
    let idBulletinBoardPage = parseInt($('#inpModalAddEditPageId').val());
    let name = $('#inpModalAddEditPageName').val();
    let duration = parseInt($('#inpModalAddEditPageDuration').val());
    let idBulletinBoard = parseInt($('#lblBoardName').attr('data-idboard'));
    if (name === ''){
        //TODO Swall
        return;
    }

    if (isNaN(duration)){
        //TODO swall
        return;
    }

    if (isNaN(idBulletinBoard)){
        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){
                boardAddPage(data.page);
                selectPage(data.page.idBulletinBoardPage);
                $('#divModalAddEditPage').modal('hide');
            } else {
                alert(data.error);
                //TODO swall
            }
            $.unblockUI();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.responseText);
            $.unblockUI();
        }
    });
}

function boardAddPage(page){
    let element = $(`<div data-idpage='${page.idBulletinBoardPage}'>
    <h5>${page.name}</h5>
    <small>${page.duration} sekund</small>
</div>`);
    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){
    $('[data-idpage]').removeClass('page-active');
    $('[data-idpage="' + id + '"]').addClass('page-active');
}



