import { Tasks } from '../../../imports/api/tasks.js';

Template.taskForm.onCreated(function() {
    this.subscribe("userList");
    this.subscribe("allTasks");
});

Template.taskForm.onRendered(function() {
    Meteor.setTimeout(function() {
        $('select').formSelect();
    }, 100);
    $('select').formSelect();
    $('.datepicker').datepicker();
    Session.set("taskNameErr", false);
    Session.set("taskUserErr", false);
    Session.set("taskDateErr", false);
    Session.set("hideCompletedTasks", true);
});

Template.taskForm.helpers({
    taskUsers: function() {
        return Meteor.users.find({});
    },
    username: function() {
        return this.profile.fullname;
    },
    usersId: function() {
        return this._id;
    },
});

Template.taskForm.events({
    'click .saveTaskMgmt' (event) {
        event.preventDefault();
        let taskName = $("#taskName").val();
        let taskUser = $("#taskUser").val();
        let taskDate = $("#taskDate").val();
        let taskUserErr = false;
        let taskNameErr = false;
        let taskDateErr = false;
        let userInfo;
        let actDate;

        console.log("taskUser value: " + taskUser);

        if (taskName == null || taskName == "") {
            taskNameErr = true;
        }

        if (taskDate == null || taskDate == "") {
            taskDateErr = true;
        } else {
            actDate = new Date(taskDate);
        }

        if (taskUser == null || taskUser == "") {;
            taskUserErr = true;
        } else {
            userInfo = taskUser.split('_');
        }

        if (taskUserErr == false && taskDateErr == false && taskNameErr == false) {
            Meteor.call("add.task", taskName, userInfo[0], userInfo[1], taskDate, actDate, function(err, result) {
                if (err) {
                    console.log("    ERROR adding the new task: " + err);
                } else {
                    console.log("    SUCCESS adding the new task.");
                    $("#taskName").val("");
                    $("#taskDate").val("");
                    $("#taskUser").val("");
                    $('select').formSelect();
                }
            });
        } else {
            showSnackbar("ERROR: Missing Required Fields!", "red");
        }
    },
    'click #hideCompletedTasks' (event) {
        let hideComp = $("#hideCompletedTasks").prop('checked');
        if (hideComp == true) {
            Session.set("hideCompletedTasks", true);
        } else {
            Session.set("hideCompletedTasks", false);
        }
        
    }
});