import { MenuItems } from '../../imports/api/menuItems.js';
import { Menus } from '../../imports/api/menu.js';
import moment from 'moment';

Template.menuItemsForm.onCreated(function() {
    this.subscribe("myMenus");
    this.subscribe("myMenuItems", Session.get("menuId"));
});

Template.menuItemsForm.onRendered(function() {
    $('.datepicker').datepicker();
    Session.set("menuItemErr", false);
});

Template.menuItemsForm.helpers({
    menuItemErr: function() {
        return Session.get("menuItemErr");
    },
    menuName: function() {
        let menuId = Session.get("menuId");
        let menuInfo = Menus.findOne({ _id: menuId });
        let menuName = menuInfo.menuName;
        return menuName;
    }
});

Template.menuItemsForm.events({
    'click .saveMenuItem' (event) {
        event.preventDefault();
        let menuItem = $("#menuItemInp").val();
        let dateSrv = $("#dateServed").val();
        let menuId = Session.get("menuId");

        if (menuItem == null || menuItem == "") {
            Session.set("menuItemErr", true);
        } else {
            Meteor.call('add.menuItem', menuItem, dateSrv, menuId, function(err, result) {
                if (err) {
                    console.log("    ERROR adding menu item: " + err);
                } else {
                    console.log("    SUCCESS adding menu item.");
                    $("#menuItemInp").val("");
                    $("#dateServed").val("");
                }
            });
        }
    },
    'click .shiftOneDay' (event) {
        event.preventDefault();
        let menuInfo = MenuItems.find({}).fetch();
        // now menuInfo is an array
        let menuInfoLen = menuInfo.length;
        for (i = 0; i < menuInfoLen; i++) {
            let menuItemId = menuInfo[i]._id;
            let momentAddDay = moment(menuInfo[i].serveDate).add(1, 'day').format("MMM DD, YYYY");
            // console.log(momentAddDay);
            Meteor.call('shiftDate', menuItemId, momentAddDay, function(err,result) {
                if (err) {
                    // console.log("    ERROR shifting meal days: " + err);
                } else {
                    // console.log("    SUCCESS shifting meal date.");
                }
            });
        }
    }
});