var chart;

$(document).ready(function() {
    $("#tabs").tabs({ active: 0 });
    $("#form_duedate").datepicker();
    $("#form_submit").click(function() { submitTask(); });
    $("#form_delete").click(function() { deleteTask(); });
    $("#form_showall").click(function() { toggleShowAll(); });
    $("#form_setcomplete").click(function() { setTaskComplete(); });
    $("#form_setincomplete").click(function() { setTaskComplete(true); });
    $("#form_cancel").click(function() { resetForm(true); });
    $("#filter_reset").click(function() { $("#form_filter").val(""); });
    $("#panelimg").click(function() { updateImage(); });
    //$("#tabs").on("tabsactivate", function(event, ui) { console.log($("#tabs").tabs('option', 'active')); });
    getTasks();
    var chartOptions = {
        chart: {
            type: 'bar',
            height: 550
        },
        plotOptions: {
           bar: {
              horizontal: false,
              columnWidth: '80%',
              endingShape: 'rounded'
           }
        },
        dataLabels: {
           enabled: false
        },
         xaxis: {
            categories: ['6','5','4','3','2','1']
         },
         yaxis: {
            title: {
               text: 'Task Count'
            }
         },
        series: [],
        noData: {
           text: 'Loading...'
        }
    }
    chart = new ApexCharts($("#chart")[0], chartOptions);
    chart.render();
    updateChart();
});

function updateImage() {
   console.log("Getting image...");
   $("#panelimg").attr("src", "image.php?"+(Math.floor(Math.random()*100000)));
   updateChart();
}

function updateChart() {
   $.ajax({
      url: 'ajax/task-getstats.php',
      dataType: 'json',
      success: function(data, stat, jqo) {
         chart.updateSeries([{
            name: 'Created',
            data: data.createdtasks
         },{
            name: 'Completed',
            data: data.completedtasks
         }])
      },
      error: function(jqo, stat, error) {
         toastr.error("Could not communicate with server!", "Server Error");
      }
   });
}

function deleteTask() {
   if ( $("#form_id").val() == "0" ) return;
   var doDelete = confirm("Are you certain you wish to delete this task?\n\nIf so then click 'OK'.")
   if ( !doDelete ) return;
   $.ajax({
      url: 'ajax/task-delete.php',
      dataType: 'json',
      data: {
         id: $("#form_id").val(),
      },
      success: function(data, stat, jqo) {
         if ( data.error ) {
            toastr.error(data.message, "Submission Error");
         } else {
            toastr.success(data.message, "Task Deleted");
            getTasks();
            updateImage();
            resetForm(true);
         }
      },
      error: function(jqo, stat, error) {
         toastr.error("Could not communicate with server!", "Server Error");
      }
   });
}

function setTaskComplete(incomplete = false) {
   if ( $("#form_id").val() == "0" ) return;
   $.ajax({
      url: 'ajax/task-setcomplete.php',
      dataType: 'json',
      data: {
         id: $("#form_id").val(),
         incomplete: (incomplete) ? 1 : 0
      },
      success: function(data, stat, jqo) {
         if ( data.error ) {
            toastr.error(data.message, "Submission Error");
         } else {
            toastr.success(data.message, "Task Complete");
            getTasks();
            updateImage();
            resetForm(true);
         }
      },
      error: function(jqo, stat, error) {
         toastr.error("Could not communicate with server!", "Server Error");
      }
   });
}

function toggleShowAll() {
   $.ajax({
      url: 'ajax/toggleshowall.php',
      dataType: 'json',
      data: {
         showall: ($("#form_showall").prop('checked')) ? 1 : 0,
      },
      success: function(data, stat, jqo) {
         if ( data.error ) {
            toastr.error(data.message, "Form Data Error");
         } else {
            toastr.success(data.message, "Task List");
            getTasks();
         }
         $("#form_showall").prop('checked', data.showall);
      },
      error: function(jqo, stat, error) {
         toastr.error("Could not communicate with server!", "Server Error");
      }
   });
}

function submitTask() {
   $.ajax({
      url: 'ajax/task-submit.php',
      dataType: 'json',
      data: {
         id: $("#form_id").val(),
         title: $("#form_title").val(),
         description: $("#form_description").val(),
         priority: $("#form_priority").val(),
         duedate: $("#form_duedate").val()
      },
      success: function(data, stat, jqo) {
         if ( data.error ) {
            toastr.error(data.message, "Form Data Error");
         } else {
            toastr.success(data.message, "Success");
            getTasks();
            resetForm(true);
            $("#form_id").val("");
            $("#form_title").val("");
            $("#form_description").val("");
            $("#form_createdate").val("Now");
            $("#form_duedate").val("");
            $("#form_completedate").html("");
            $("#form_completerow").addClass("noshow");
            $("#column_deletebutton").addClass("noshow");
            $("#column_incompletebutton").addClass("noshow");
            $("#column_completebutton").addClass("noshow");
            updateImage();
         }
      },
      error: function(jqo, stat, error) {
         toastr.error("Could not communicate with server!", "Server Error");
      }
   });
}

function resetForm(backToTasks = false) {
   if ( backToTasks ) $("#tabs").tabs("option", "active", 0);
   $("#form_id").val("");
   $("#form_title").val("");
   $("#form_description").val("");
   $("#form_createdate").val("Now");
   $("#form_duedate").val("");
   $("#form_completedate").html("");
   $("#form_completerow").addClass("noshow");
   $("#column_deletebutton").addClass("noshow");
   $("#column_incompletebutton").addClass("noshow");
   $("#column_completebutton").addClass("noshow");
}

function getTasks() {
   $.ajax({
      url: 'ajax/task-list.php',
      dataType: 'json',
      success: function(data, stat, jqo) {
         $("#form_showall").prop('checked', data.showalltasks);
         var show = "";
         data.tasks.forEach(function(task, index) {
            show += "<div class='task' id='task_" + task.id + "'>";
            show += "<div><span class='strongtext'>Title: </span>" + task.title_safe + "</div>";
            show += "<div><span class='strongtext'>Description: </span>" + task.description_safe + "</div>";
            show += "<div><span class='strongtext'>Priority: </span>" + task.priority + "</div>";
            show += "<div><span class='strongtext'>Created On: </span>" + task.createdate + "</div>";
            show += "<div><span class='strongtext'>Due Date: </span>" + task.duedate + "</div>";
            show += "<div><span class='strongtext'>Days Left: </span>" + task.daysleft + "</div>";
            show += "</div>";
         });
         $("#tasklist").html(show);
         data.tasks.forEach(function(task, index) {
            $("#task_"+task.id).click(function() {
               editTask(task.id);
            });
         });
      },
      error: function(jqo, stat, error) {
         toastr.error("Could not communicate with server!", "Server Error");
      }
   });
}

function editTask(taskId) {
   $.ajax({
      url: 'ajax/task-get.php',
      dataType: 'json',
      data: {
         id: taskId
      },
      success: function(data, stat, jqo) {
         if ( !data.error ) {
            $("#form_id").val(data.task.id);
            $("#form_title").val(data.task.title);
            $("#form_description").val(data.task.description);
            $("#form_priority").val(data.task.priority);
            $("#form_duedate").val(data.task.duedate);
            $("#form_createdate").text(data.task.createdate);
            if ( data.task.completed ) {
                $("#form_createrow").removeClass("noshow");
                $("#column_incompletebutton").removeClass("noshow");
                $("#column_completebutton").addClass("noshow");
            } else {
                $("#column_completebutton").removeClass("noshow");
            }
            $("#column_deletebutton").removeClass("noshow");
            $("#tabs").tabs("option", "active", 1);
            updateImage();
         } else {
            toastr.warn("Task not found!", "Task Error");
         }
      },
      error: function(jqo, stat, error) {
         toastr.error("Could not communicate with server!", "Server Error");
      }
   });
}

// vim: ts=3 sw=3:
