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

Template.myTasksTbl.onCreated(function() {
    this.subscribe("myTasks");
});

Template.myTasksTbl.onRendered(function() {
    $('.collapsible').collapsible();
    Session.set("hideComplete", true);
    Session.set("onlyToday", true);
});

Template.myTasksTbl.helpers({
    tasks: function() {
        let onlyToday = Session.get("onlyToday");
        let hide = Session.get("hideComplete");
        let todayIs = moment(new Date()).format("MMM DD, YYYY");
        if (hide == true && onlyToday == false) {
            return TaskItems.find({ isComplete: false }, { sort: { actualDate: 1 }});
        } else if (hide == true && onlyToday == true) {
            return TaskItems.find({ isComplete: false, taskDate: todayIs }, { sort: { actualDate: 1 }});
        } else if (hide == false && onlyToday == true) {
            return TaskItems.find({ taskDate: todayIs }, { sort: { actualDate: 1 }});
        } else {
            return TaskItems.find({}, { sort: { actualDate: 1 }});
        }
    },
    passedDate: function() {
        let taskDate = new Date(this.taskDate);
        let now = new Date()
        let diff = now < taskDate;
        let comp = this.isComplete;
        if (diff == false && comp == false) {
            return false;
        } else {
            return true;
        }
    },
    compOn: function() {
        if (this.isComplete == true) {
            return moment(this.completedOn).format("MMM DD, YYYY");
        }
    }
});

Template.myTasksTbl.events({
    'click .markMyTaskComplete' (event) {
        event.preventDefault();
        let taskId = this._id;
        Meteor.call("markTask.complete", taskId, function(err, result) {
            if (err) {
                console.log("    ERROR marking task completeL " + err);
                showSnackbar("ERROR Marking Task Complete!", "red");
            } else {
                showSnackbar("Successfully Marked Task Complete!", "green");

            }
        });
    },
    'click .deleteMyTask' (event) {
        event.preventDefault();
        Session.set("deleteId", this._id);
        Session.set("method", "delete.task");
        Session.set("item", this.taskName);
        Session.set("view", "My Tasks");
        $('#modalDelete').modal('open');
    }
});