import { ListItems } from '../../imports/api/listItems.js'
import { Lists } from '../../imports/api/lists.js';
import { Products } from '../../imports/api/products.js';

Template.listItemsForm.onCreated(function() {
    this.subscribe("myListItems", Session.get("listId"));
    this.subscribe("myLists");
    this.subscribe("myProducts");
});

Template.listItemsForm.onRendered(function() {
    Meteor.setTimeout(function() {
        $('select').formSelect();
    }, 100);
    $('select').formSelect();
    Session.set("listItemEditMode", false);
    Session.set("itemReqErr", false);
    Session.set("showReceivedItems", false);
});

Template.listItemsForm.helpers({
    selListName: function() {
        let selListId = Session.get("listId");
        console.log("List ID in Helper is: " + selListId);
        let listInfo = Lists.findOne({ _id: selListId });
        return listInfo.listName;
    },
    itemProdName: function() {
        return Products.find({});
    },
    editMode: function() {
        return Session.get("listItemEditMode");
    }
});

Template.listItemsForm.events({
    'click .saveListItem' (event) {
        event.preventDefault();
        let item = $("#listItems").val();
        let listId = Session.get("listId");
        if (item == null || item == "") {
            Session.set("itemReqErr", true);
        } else {
            Meteor.call("add.listItem", item, listId, function(err, result) {
                if (err) {
                    console.log("    ERROR adding item to list: " + err);
                } else {
                    console.log("    SUCCESS adding item to list.");
                    $("#listItems").val("");
                }
            });
        }
    },
    'keydown #listItems' (event) {
        if (event.which === 13) {
            let item = $("#listItems").val();
            let listId = Session.get("listId");
            if (item == null || item == "") {
                Session.set("itemReqErr", true);
            } else {
                Meteor.call("add.listItem", item, listId, function(err, result) {
                    if (err) {
                        console.log("    ERROR adding item to list: " + err);
                    } else {
                        console.log("    SUCCESS adding item to list.");
                        $("#listItems").val("");
                    }
                });
            }
        }
    },
    'click #showReceivedItems' (event) {
        if ($("#showReceivedItems").prop('checked') == true) {
            Session.set("showReceivedItems", true);
        } else {
            Session.set("showReceivedItems", false);
        }
    }
});