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

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

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

Template.listItemsTbl.helpers({
    'thisListItems': function() {
        let showRecvd = Session.get("showReceivedItems");
        let searchVal = Session.get("searchVal");;
        if (showRecvd == false) {
            if (typeof searchVal == 'undefined' || searchVal.length === 0) {
                return ListItems.find({ itemReceived: false });
            } else {
                return ListItems.find({ itemReceived: false, itemName: { $regex: searchVal + '.*', $options: 'i' } });
            }
        } else {
            if (typeof searchVal == 'undefined' || searchVal.length == 0) {
                return ListItems.find({});
            } else {
                return ListItems.find({ itemName: { $regex: searchVal + '.*', $options: 'i' } });
            }
        }
    },
});

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();
        Session.set("deleteId", this._id);
        Session.set("method", "delete.listItem");
        Session.set("item", this.itemName);
        Session.set("view", "List Items");
        $('#modalDelete').modal('open');
    },
});