/**
 * Created by Cyan on 3/13/2016.
 */

// Element position before drag and drop
var taskIndex;

$(document).ready(function() {
    loadBacklogFixedEvents();

    // Get tasks
    getBacklogTasks();

    loadBacklogEvents();
});

function loadBacklogFixedEvents() {
    // Select tab
    $('.nav li.active').removeClass('selected');
    $('#backlog-tab').addClass('selected');

    // Get tasks by search
    $('.search').click(getGenericTasks);

    // Remove search
    $('.remove-search').click(removeSearch);

    // Create task
    $('form#add-task').submit(createTask);

    // Clear modal
    $('.add-task-btn').click(clearModal);
}

function loadBacklogEvents() {
    // Show text area
    $('#summernote').summernote({
        toolbar: [
            // [groupName, [list of button]]
            ['style', ['bold', 'italic', 'underline', 'clear']],
            ['font', ['strikethrough', 'superscript', 'subscript']],
            ['para', ['ul', 'ol', 'paragraph']],
        ],
        minHeight: 300,
        placeholder: 'Insert description here...'
    });

    // Borramos el summernote
    $('#summernote').summernote('code', '');

    // Drag and drop
    $(function() {
        $( "#sortable" ).sortable({
            start: function(event, ui) {
                taskIndex = $('.backlog-list > li').index(ui.item) + 1;
            },

            stop: function(event, ui) {
                var index = $('.backlog-list > li').index(ui.item) + 1;
                var id = $(ui.item).find('.item-ref .content').text();

                if (index != taskIndex) {
                    updatePriority(id, index);
                }
            }
        });
    });

    // Task acordeon
    $('.panel-heading').click(acordeonExtraContent);

    // Stop events for selects of task
    $('.item-state select').click(function(event) {
        event.stopPropagation();
        event.preventDefault();
    });

    // Stop events for points of task
    $('input#points').click(function(event) {
        event.stopPropagation();
        event.preventDefault();
    });

    // Delete task
    $('.delete-task').click(deleteTask);

    // On cost change
    $('.item-cost input#points').change(updateCost);

    // Update Assigned to
    $('.assigned-member select').change(updateAssignedTo);

    // Update state
    $('.item-state select').change(updateState);

    // Tag on hover
    $('.tag-element').hover(function() {
        $(this).find('.delete-tag').show();
    }, function() {
        $(this).find('.delete-tag').hide();
    });

    // Remove tag
    $('.tag-element').click(removeTag);

    // Show add tag
    $('.glyphicon-plus').click(function() {
         $(this).siblings('input#addTag').show();
         $(this).siblings('input#addTag').focus();
         $(this).hide();
    });

    // Add tag - focus out
    $('input#addTag').focusout(addTag);
}

function removeSearch() {
    $('.search-bar .form-control').val('');
    getBacklogTasks();
}

function getGenericTasks() {
    var tags = $('.search-bar .form-control').val().replace(/\s{2,}/g, ' ');

    if (!tags) {
        getBacklogTasks();
    } else if (tags.indexOf("#") == 0) {
        getSearchTasksById(tags.substring(1));
    } else {
        tags = tags.split(' ');
        getSearchTasksByTags(tags);
    }
}

function getBacklogTasks() {
    var token = $("input[name='_csrf']").val();

    $.ajax({
        type: "GET",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/backlog/tasks",
        success: function(data){
            $('div.tasks-content').html(data);
            loadBacklogEvents();
            $('#sortable').sortable("enable");
        },

        error: function(e){
            showErrorMessage('Can not get the backlog tasks.');
        }
    });
}

function getSearchTasksById(tag) {
    var token = $("input[name='_csrf']").val();

    $.ajax({
        type: "GET",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/backlog/searchById",
        data: {"searchField" : tag.toString()},
        success: function(data){
            $('div.tasks-content').html(data);
            loadBacklogEvents();
            $('#sortable').sortable("disable");
        },

        error: function(e){
            showErrorMessage('Can not get the tasks.');
        }
    });
}

function getSearchTasksByTags(tags) {
    var token = $("input[name='_csrf']").val();

    $.ajax({
        type: "GET",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/backlog/searchByTags",
        data: {"searchField" : tags.toString()},
        success: function(data){
            $('div.tasks-content').html(data);
            loadBacklogEvents();
            $('#sortable').sortable("disable");
        },

        error: function(e){
            showErrorMessage('Can not get the tasks.');
        }
    });
}

function acordeonExtraContent(event) {
    var extraContent = $(this).siblings('.extra-content');

    if ($(extraContent).hasClass('hidden')) {
        $(extraContent).show();
        $(extraContent).removeClass('hidden');
        $(extraContent).addClass('showing');
    } else {
        $(extraContent).hide();
        $(extraContent).removeClass('showing');
        $(extraContent).addClass('hidden');
    }

    event.stopPropagation();
    event.preventDefault();
}

function createTask(event) {
    event.preventDefault();

    var token = $("input[name='_csrf']").val();
    var type = $('.taskType select option:selected').val();
    var title = $('input#taskTitle').val();
    var cost = $('input#taskCost').val();
    var tags = $('input#taskTags').val().replace(/\s{2,}/g, ' ');
    var assignedTo = $('.assignMemberTask select option:selected').val();
    var description = $('#summernote').summernote('code');;
    var priority = $('li.item').size();

    var task = {};

    if (tags) {
        tags = tags.split(' ');
        task['tags'] = tags;
        var ok = true;

        $(tags).each(function() {
           if ($(this).length > 15) {
               ok = false;
           }
        });

        if (!ok) {
            $('#add-task-modal .message').text('Max tag length is 15.');
            $('#add-task-modal .alert-danger').show();
            return;
        }
    }

    if (description.length > 1000) {
        $('#add-task-modal .message').text('Max description length must be 1000 chars.');
        $('#add-task-modal .alert-danger').show();
        return;
    } else if (tags.length > 3) {
        $('#add-task-modal .message').text('Max tags number is 3.');
        $('#add-task-modal .alert-danger').show();
        return;
    }

    task['title'] = title;
    task['priority'] = priority;

    if (assignedTo) {
        task['assignedTo'] = assignedTo;
    }

    if (description) {
        task['description'] = description;
    }

    if (cost) {
        task['points'] = cost;
    }

    if (type) {
        task['type'] = type;
    }

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/backlog/createTask",
        data: JSON.stringify(task),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if (data['state'] === "OK") {
                getGenericTasks();
                showSuccessMessage(data['message']);
            } else {
                showErrorMessage(data['message']);
            }
        },
        error: function(data) {
            showErrorMessage('Can not create the task.');
        }
    });

    // Close the modal
    $('#add-task-close').click();
}

function clearModal() {
    $('#add-task-modal .alert-danger').hide();
    $('#add-task option:first').attr('selected', 'selected');
    $('#add-task select').val($('#add-task option:first').val());
    $('.assignMemberTask option:first').attr('selected', 'selected');
    $('.assignMemberTask select').val($('.assignMemberTask option:first').val());
    $('#summernote').summernote('code', '');
    $('input#taskTitle').val('');
    $('input#taskCost').val('');
    $('input#taskTags').val('');
}

function deleteTask(event) {
    event.stopPropagation();
    event.preventDefault();

    var token = $("input[name='_csrf']").val();
    var taskElement = $(this).closest('.item');
    var id = $(this).parent().find('.item-ref-content').text().substr(1);

    var currentItem = $(this).closest('li.item');
    var priority = $('.backlog-list > li').index(currentItem);

    var task = {};
    task['id'] = id;
    task['priority'] = priority;

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/backlog/deleteTask",
        data: JSON.stringify(task),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if ("OK" === data['state'])  {
                removeTaskElement(taskElement);
                showSuccessMessage(data['message']);
            } else {
                showErrorMessage(data['message']);
            }
        },
        error: function(data) {
            showErrorMessage('Can not delete the task.');
        }
    });
}

function removeTaskElement(task) {
    $(task).hide();
    $(task).remove();
}

function updatePriority(id, index) {
    var token = $("input[name='_csrf']").val();

    var task = {};
    task['id'] = id.substring(1);
    task['previousPriority'] = taskIndex;
    task['currentPriority'] = index;

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/backlog/updateTaskPriority",
        data: JSON.stringify(task),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if ("KO" == data['state'])  {
                showErrorMessage(data['message']);
            }
        },
        error: function(data) {
            showErrorMessage('Can not update the priority.');
        }
    });
}

function updateCost(event) {
    var token = $("input[name='_csrf']").val();
    var id = $(this).closest('.title-info-list').find('.item-ref-content').text();
    var cost = $(this).val();

    if (cost < 0 || cost > 300) {
        showErrorMessage('The cost must be bettwen 0 and 300.');
        return;
    }

    var task = {};
    task['id'] = id.substring(1);
    task['points'] = cost;

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/backlog/updateTaskCost",
        data: JSON.stringify(task),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if ("KO" == data['state'])  {
                showErrorMessage(data['message']);
            }
        },
        error: function(data) {
            showErrorMessage('Can not update the cost.');
        }
    });
}

function updateAssignedTo(event) {
    var token = $("input[name='_csrf']").val();
    var id = $(this).closest('.item').find('.item-ref-content').text();
    var email = $(this).find('option:selected').val();

    var task = {};
    task['id'] = id.substring(1);
    task['assignedTo'] = email;

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/backlog/updateTaskAssignTo",
        data: JSON.stringify(task),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if ("KO" == data['state'])  {
                showErrorMessage(data['message']);
            }
        },
        error: function(data) {
            showErrorMessage('Can not assign the member to the task.');
        }
    });
}

function updateState(event) {
    var selectObj = $(this);

    var token = $("input[name='_csrf']").val();
    var id = $(this).closest('.item').find('.item-ref-content').text();
    var state = $(this).find('option:selected').val();

    var task = {};
    task['id'] = id.substring(1);
    task['state'] = state;

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/backlog/updateTaskState",
        data: JSON.stringify(task),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if ("KO" == data['state'])  {
                showErrorMessage(data['message']);
            } else {
                if (state == 'Blocked') {
                    $(selectObj).closest('.item').find('.item-progress-content .progress-bar').width('25%');
                    $(selectObj).closest('.item > .panel').removeClass('panel-info');
                    $(selectObj).closest('.item > .panel').addClass('panel-default');
                } else if (state == 'To do') {
                    $(selectObj).closest('.item').find('.item-progress-content .progress-bar').width('0%');
                    $(selectObj).closest('.item > .panel').removeClass('panel-default');
                    $(selectObj).closest('.item > .panel').addClass('panel-info');
                } else if (state == 'In progress') {
                    $(selectObj).closest('.item').find('.item-progress-content .progress-bar').width('50%');
                    $(selectObj).closest('.item > .panel').removeClass('panel-default');
                    $(selectObj).closest('.item > .panel').addClass('panel-info');
                } else {
                    $(selectObj).closest('.item').find('.item-progress-content .progress-bar').width('100%');
                    $(selectObj).closest('.item > .panel').removeClass('panel-default');
                    $(selectObj).closest('.item > .panel').addClass('panel-info');
                }
            }
        },
        error: function(data) {
            showErrorMessage('Can not update the state of the task.');
        }
    });
}

function addTag(event) {
    var inputObj = $(this);
    var token = $("input[name='_csrf']").val();
    var id = $(this).closest('.panel').find('.item-ref-content').text();
    var totalTags = $(this).parent().find('.label').length;
    var tag = $(this).val().replace(/\s{2,}/g, ' ');

    // Hide the input and show the add tag label
    $(this).hide();
    $(this).val('');
    $(this).siblings('.glyphicon-plus').show();

    if (tag.trim()) {
        tag = tag.split(' ');
    } else {
        return;
    }

    if (totalTags > 2) {
        showErrorMessage('You can have only 3 tags.');
        return;
    } else if (tag.length > 1) {
        showErrorMessage('You have to insert only one tag.');
        return;
    }

    var task = {};
    task['id'] = id.substring(1);
    task['tags'] = tag;

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/backlog/addTaskTag",
        data: JSON.stringify(task),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if ("KO" == data['state'])  {
                showErrorMessage(data['message']);
            } else {
                addTagElement(inputObj, tag[0]);
            }
        },
        error: function(data) {
            showErrorMessage('Can not add the tag.');
        }
    });
}

function addTagElement(input, tagName) {
    var tagElement = "<div class='tag-element'>" +
                        "<span class='label label-warning'>" +
                            "<span class='tag-name'>" + tagName + ' ' + "</span>" +
                            "<span class='glyphicon glyphicon-remove delete-tag' style='display: none'></span>" +
                        "</span>" +
                    "</div>";

    if ($(input).parent().find('.tag-element').size() > 0) {
        $(input).parent().find('.tag-element:last').after(tagElement);
    } else {
        $(input).parent().prepend(tagElement);
    }

    // Tag on hover
    $(input).parent().find('.tag-element:last').hover(function() {
        $(this).find('.delete-tag').show();
    }, function() {
        $(this).find('.delete-tag').hide();
    });

    // Add remove tag event
    $(input).parent().find('.tag-element:last').click(removeTag);
}

function removeTag(event) {
    var tagObj = $(this);
    var token = $("input[name='_csrf']").val();
    var id = $(this).closest('.item').find('.item-ref-content').text();
    var tag = $(this).text().trim().replace(/\s{2,}/g, ' ').split(' ');

    var task = {};
    task['id'] = id.substring(1);
    task['tags'] = tag;

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/backlog/deleteTaskTag",
        data: JSON.stringify(task),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if ("KO" == data['state'])  {
                showErrorMessage(data['message']);
            } else {
                $(tagObj).hide();
                $(tagObj).remove();
            }
        },
        error: function(data) {
            showErrorMessage('Can not delete the tag.');
        }
    });
}