var express = require("express");
var router = express.Router({ mergeParams: true });
var Product = require("../models/product");
var Cart = require("../models/cart");

//get current user cart
router.get("/user/signed/cart", function (req, res) {
    Cart.findOne({User: req.user}, function (err, cart) {
        if (err) { console.log(err); return res.redirect("/home"); }
res.json({message:"success", cart});
    });
})

//get products for cart
router.post("/cart_products", function (req, res) {
    var ids = [];
    var full_products_cart = [];
    var cart_products = req.body.cart_products;
    cart_products.forEach(cart_product => {
        ids.push(cart_product._id);
    });
    Product.find({ _id: { $in: ids } }, function (err, products) {
        if (err) { console.log(err); return res.json({ message: "fail" }); }
        var full_product_cart;
        for (var i = 0; i < products.length; i++) {
            for (var j = 0; j < cart_products.length; j++) {
                if (products[i]._id == cart_products[j]._id) {
                    full_product_cart = { product: products[i], qty: cart_products[j].qty }
                    full_products_cart.push(full_product_cart);
                }
            }
        }

        if (req.user) {

            Cart.findOne({ User: req.user }).populate("Product_qty.product").exec(function (err, cart) {
                if (err) { console.log(err); return res.redirect("/home"); }
                if (!cart) {
                    Cart.create({ User: req.user, Product_qty: full_products_cart }, function (err, nCart) {
                        if (err) { console.log(err); return res.redirect("/"); }
                        console.log("first", cart);
                        return res.json({ message: "success", full_products_cart: nCart.Product_qty });
                    });
                }
                else {
                    console.log("exists", cart);
                    return res.json({ message: "success", full_products_cart: cart.Product_qty });
                }
            });

        }
        else res.json({ message: "success", full_products_cart });

    });
})

//add product to cart
router.post("/new/cart/product", function (req, res) {
    console.log(req.body);
    var cart_product = req.body.cart_product;
    Cart.findOne({ User: req.user }, function (err, cart) {
        if (err) { console.log(err); return res.redirect("/home"); }
        Product.findOne({ _id: cart_product._id }, function (err, product) {
            if (err) { console.log(err); return res.redirect("/home"); }
            if (!cart) {
                Cart.create({}, function (err, nCart) {
                    if (err) { console.log(err); return res.redirect("/home"); }
                    nCart.Product_qty.push({ product, qty: cart_product.qty });
                    nCart.save(function () {
                        return res.json({ message: "success" });
                    })
                });
            }
            else {
                Cart.findOne({ User: req.user, "Product_qty.product": product }).exec(function (err, fCart) {
                    if (err) { console.log(err); return res.redirect("/home"); }
                    if (fCart) {
                        console.log("found");
                        for (var i = 0; i < fCart.Product_qty.length; i++) {
                            if (fCart.Product_qty[i].product.toString() == product._id.toString()) {
                                fCart.Product_qty[i].qty += cart_product.qty;
                                console.log(fCart.Product_qty[i].product, product._id);
                            }
                        }
                        fCart.save(function () {
                            return res.json({ message: "success" });
                        });
                    }
                    else {
                        cart.Product_qty.push({ product, qty: cart_product.qty });
                        cart.save(function () {
                            return res.json({ message: "success" });
                        })
                    }
                });
            }
        });

    })
})

//change cart product quantity
router.post("/cart/product_quantity", function (req, res) {
    Cart.findOne({ User: req.user }, function (err, cart) {
        if (err) { console.log(err); return res.redirect("/home"); }
        cart.Product_qty.find(cart_product => cart_product.product.toString() == req.body.product_id.toString()).qty = req.body.qty;
        cart.save(function () {
            return res.json({ message: "success" });
        })
    });
})

//remove product from cart
router.delete("/cart/remove/product/:product_id", function (req, res) {
    Cart.findOne({ User: req.user }, function (err, cart) {
        if (err) { console.log(err); return res.redirect("/home"); }
        cart.Product_qty = cart.Product_qty.filter(function (cart_product) {
            return cart_product.product.toString() !== req.params.product_id.toString();
          });
        cart.save(function () {
            return res.json({ message: "success" });
        })
    });
})


module.exports = router;