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

$(document).ready(function() {
    loadGenericProjectsEvents();
    getProjects();
});

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

    // Create project
    $('form#add-project-form').submit(createProject);

    // Alert message
    $('.alert .glyphicon').click(function() {
        $(this).parent().hide();
    });

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

function loadProjectsEvents() {
    // Load project
    $('.load-project-btn').click(loadProject);

    // Delete project
    $('.delete-project').click(deleteProject);

    // Unfollow project
    $('.unfollow-project-btn').click(unfollowProject);
}

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

    $.ajax({
        type: "GET",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/projects/getProjects",
        async: true,
        success: function(data){
            $('div.projects-list').html(data);
            loadProjectsEvents();
        },

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

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

    var request = {}
    var token = $("input[name='_csrf']").val();
    var project = $('input#projectName').val();
    var role = $('input#role').val();

    request['project'] = project;
    request['role'] = role;

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

    $('#add-project-close').click();
}

function deleteProject(event) {
    var token = $("input[name='_csrf']").val();
    var project = $(this).siblings('.project-name').text();

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'text/plain'
        },
        url: "/projects/deleteProject",
        data: project,
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if ("OK" === data['state'])  {
                getProjects();
                showSuccessMessage(data['message']);
            } else {
                showErrorMessage(data['message']);
            }
        },
        error: function(data) {
            showErrorMessage('Can not remove the project.')
        }
    });
}

function loadProject(){
    var token = $("input[name='_csrf']").val();
    var project = $(this).closest('.panel-info').find('.project-name').text();
    var loadBtn = $(this);

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'text/plain'
        },
        url: "/projects/loadProject",
        data: project,
        dataType: "text",
        timeout: 100000,
        success: function(data) {
            $('.load-project-btn').text("Load project");
            $('.load-project-btn').removeClass("btn-success");
            $('.load-project-btn').addClass("btn-secondary");

            loadBtn.text("Project loaded");
            loadBtn.removeClass("btn-success");
            loadBtn.addClass("btn-success");
            showSuccessMessage("Project loaded. ");
        },

        error: function(data) {
            showErrorMessage("Can not load the project.");
        }
    });
}

function unfollowProject(event) {
    var token = $("input[name='_csrf']").val();
    var project = $(this).closest('.project').find('.project-name').text();

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'text/plain'
        },
        url: "/projects/unfollowProject",
        data: project,
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if ("OK" === data['state'])  {
                getProjects();
                showSuccessMessage(data['message']);
            } else {
                showErrorMessage(data['message']);
            }
        },
        error: function(data) {
            showErrorMessage('Can not unfollow the project.')
        }
    });
}

function clearModal() {
    $('input#projectName').val('');
    $('input#role').val('');
}