// selectedBlog = [id, blog_id, description, status]
const selectedBlog = [];

// Current state
let currentPageNo = 1;
let currentPageSize = 10;
const filterParams = {
    blog_id: 0,
    description: '',
    status: -1
};

$('#add-form').submit(function(e){
    e.preventDefault();

    const inputs = $('#add-form input, #add-form select');
    const data = {};

    inputs.each(function() {
        data[this.name] = $(this).val();
    });

    $.ajax({
        method: 'post',
        url: '/blog/store',
        dataType: 'json',
        data: data,

        success: function(res) {
            loadPage(filterParams);
            alert(res.message);
        },

        error: function(err) {
            alertErr(err.responseJSON.errors);
        }
    });
});

$('#update-form').submit(function(e){
    e.preventDefault();

    const inputs = $('#update-form input, #update-form select');
    const data = {};

    inputs.each(function() {
        data[this.name] = $(this).val();
    });

    $.ajax({
        method: 'post',
        url: '/blog/update',
        dataType: 'json',
        data: data,

        success: function(res) {
            loadPage(filterParams);
            alert(res.message);
        },

        error: function(err) {
            alertErr(err.responseJSON.errors);
        }
    });
});

$('#filter-form').submit(function(e){
    e.preventDefault();

    const inputs = $('#filter-form input, #filter-form select');

    inputs.each(function() {
        filterParams[this.name] = $(this).val();
    });

    // Set pageNo back to 1 when filter blogs
    currentPageNo = 1;

    loadPage(filterParams);
});

function deleteBlog(el) {
    const r = confirm('Are you sure?');

    if(r === false) {
        return;
    }

    const data = {
        id: $(el).data('id')
    };
    
    $.ajax({
        method: 'post',
        url: '/blog/delete',
        dataType: 'json',
        data: data,

        success: function(res) {
            loadPage(filterParams);
        },

        error: function(err) {
            alertErr(err.responseJSON.errors);
        }
    });
}

function bindRowSelectEvent() {
    $('#blog-table tr').click(function(e) {
        if($(e.target)[0].tagName.toLowerCase() === 'button' || !$(e.target).parent().data('id')) {
            return;
        }

        $('#add-form-wrapper').hide();
        $('#update-form-wrapper').show();

        selectedBlog[0] = $(this).data('id');
        selectedBlog[1] = $(this).find('td').eq(0).text();
        selectedBlog[2] = $(this).find('td').eq(1).text();
        selectedBlog[3] = $(this).find('td').eq(2).data('status');

        const inputs = $('#update-form input, #update-form select');

        $.each(selectedBlog, function(index, value) {
            $(inputs[index]).val(value);
        });
    });
}

function showAddForm() {
    $('#add-form-wrapper').show();
    $('#update-form-wrapper').hide();
}

function loadPage(params = null) {
    $('#blog-table').hide();
    $('#blog-table-loading').show();

    const data = {
        pageNo: currentPageNo,
        pageSize: currentPageSize
    };

    if(params) {
        data.params = params;
    }

    $.ajax({
        method: 'post',
        url: '/blog/getBlogs',
        dataType: 'json',
        data: data,

        success: function(res) {
            $('#blog-table').show();
            $('#blog-table-loading').hide();

            if (res.result.length === 0 && res.pageNo > 0) {
                currentPageNo--;
                return loadPage(filterParams);
            }

            renderBlogTable(res.result);
            renderPagination(res.total, res.pageSize, res.pageNo + 1);
        },
        
        error: function(err) {
            $('#blog-table').show();
            $('#blog-table-loading').hide();

            alertErr(err.responseJSON.errors);
        }
    });
}

function getBlogs(params = null, pageNo = 1, pageSize = 10) {
    $('#blog-table').hide();
    $('#blog-table-loading').show();

    const data = {
        params,
        pageNo,
        pageSize
    };
    
    $.ajax({
        method: 'post',
        url: '/blog/getBlogs',
        dataType: 'json',
        data: data,

        success: function(res) {
            $('#blog-table').show();
            $('#blog-table-loading').hide();

            renderBlogTable(res.result);
        },
        
        error: function(err) {
            $('#blog-table').show();
            $('#blog-table-loading').hide();

            alertErr(err.responseJSON.errors);
        }
    });
}

function renderBlogTable(result) {
    $('#blog-table tbody').empty();

    if (result.length === 0) {
        const tr = "<tr><td>No result</td><td>No result</td><td>No result</td><td>No result</td></tr>";
        $('#blog-table tbody').append(tr);
        return;
    }

    for (index in result) {
        var id = result[index].id;
        var blog_id = result[index].blog_id;
        var description = result[index].description;
        var status = result[index].status;

        var tr = `<tr data-id="${id}" style='cursor: pointer'>`;
        tr += `<td>${blog_id}</td>`;
        tr += `<td>${description}</td>`;
        tr += `<td data-status="${status}" style="text-align:center">${status == 1 ? 'Active' : 'Inactive'}</td>`;
        tr += `<td><button data-id="${id}" class="btn btn-danger" onclick="deleteBlog(this)">Delete</button></td>`;
        tr += "</tr>";

        $('#blog-table tbody').append(tr);
    }

    bindRowSelectEvent();
}

function renderPagination(total, pageSize, pageNo = 1) {
    $('#blog-pagination').empty();
    $('#blog-pagination').unbind('page');
    $('#blog-pagination').bootpag({
        total: Math.ceil(total / pageSize),
        page: pageNo,
        maxVisible: 5,
        leaps: true,
        firstLastUse: true,
        first: '←',
        last: '→',
        wrapClass: 'pagination',
        activeClass: 'active',
        disabledClass: 'disabled',
        nextClass: 'next',
        prevClass: 'prev',
        lastClass: 'last',
        firstClass: 'first'
    }).on("page", function(event, pageNo) {
        // Save current state for loadPage function
        currentPageNo = pageNo;
        currentPageSize = pageSize;

        getBlogs(filterParams, pageNo, pageSize);
    });
}

function alertErr(err) {
    const errors = Object.values(err);
    let message = '';
    
    for (index in errors) {
        message += errors[index] + ' ';
    }

    alert(message);
}