import { Products } from '../../../imports/api/products.js';

Template.prodMgmtTbl.onCreated(function() {
    this.subscribe("myProducts");
});

Template.prodMgmtTbl.onRendered(function() {
    Meteor.setTimeout(function() {
        $('.tooltipped').tooltip();
    }, 150);
    Session.set("searchProds", false);
});

Template.prodMgmtTbl.helpers({
    products: function() {
        let searchVal = Session.get("searchVal");
        if (typeof searchVal == 'undefined' || searchVal.length == 0) {
            return Products.find({});
        } else {
            return Products.find({ prodName: { $regex: searchVal + '.*', $options: 'i' } });
        }
    },
    searchProd: function() {
        return Session.get("searchProds");
    }
});

Template.prodMgmtTbl.events({
    'click .deleteProduct' (event) {
        event.preventDefault();
        Session.set("deleteId", this._id);
        Session.set("method", "delete.product");
        Session.set("item", this.prodName);
        Session.set("view", "Products");;
        $('#modalDelete').modal('open');
    },
    'click .editProduct' (event) {
        event.preventDefault();
        Session.set("prodEditMode", true);
        Session.set("prodEditId", this._id);
        let prodInfo = Products.findOne({ _id: this._id });
        $("#prodName").val(prodInfo.prodName);
        $("#prodCategory").val(prodInfo.prodCategory);
        $("#prodLocation").val(prodInfo.prodLocation);
        $("#prodStore").val(prodInfo.prodStore);
        $('select').formSelect();
    },
    'click #filterProds' (event) {
        event.preventDefault();
        Session.set("searchProds", true);
    },
    'click #closeFilter' (event) {
        event.preventDefault();
        Session.set("searchProds", false);
    },
    "keyup #searchProds" (event) {
        if (event.which !== 13) {
            let searchVal = $("#searchProds").val();
            Session.set("searchVal", searchVal);
        }
    }
});