import { ListItems } from '../../imports/api/listItems.js';

Template.listItemsTbl.onCreated(function() {
    this.autorun( () => {
        this.subscribe("myListItems", Session.get("listId"));
    });
});

Template.listItemsTbl.onRendered(function() {
    Session.set("showReceivedItems", false);
});

Template.listItemsTbl.helpers({
    'thisListItems': function() {
        let showRecvd = Session.get("showReceivedItems");
        console.log("Show Received is: " + showRecvd);
        if (showRecvd == false) {
            return ListItems.find({ itemReceived: false });
        } else {
            return ListItems.find({});
        }
    },
});

Template.listItemsTbl.events({
    'click li' (event) {
        event.preventDefault();
        let itemInfo = ListItems.findOne({ _id: this._id });
        if (itemInfo.itemOrdered == true) {
            Meteor.call('setNotOrdered.listItem', this._id, function(err, result) {
                if (err) {
                    console.log("    ERROR setting this item as NOT ordered: " + err);
                } else {
                    console.log("    SUCCESS setting this item as NOT ordered.");
                }
            });
        } else {
            Meteor.call('setOrdered.listItem', this._id, function(err, result) {
                if (err) {
                    console.log("    ERROR marking item ordered: " + err);
                } else {
                    console.log("    SUCCESS marking this item ordered.");
                }
            });
        }
    },
    'click .markListItemReceived' (event) {
        event.preventDefault();
        Meteor.call('setReceived.listItem', this._id, function(err, result) {
            if (err) {
                console.log("    ERROR setting item as received: " + err);
            } else {
                console.log("    SUCCESS setting item received.");
            }
        });
    },
    'click .deleteListItem' (event) {
        event.preventDefault();
        Meteor.call('delete.listItem', this._id, function(err, result) {
            if (err) {
                console.log("    ERROR deleting the list item: " + err);
            } else {
                console.log("    SUCCESS deleting the list item.");
            }
        });
    }
});