var express = require("express");
var router = express.Router({ mergeParams: true });
var Product = require("../models/product");
var Sub_item = require("../models/sub_item");
var Category = require("../models/category");
let file_manager = require("../tools/file_managment");
let { storageFun } = require("../tools/multer");
//const SocialPost = require("social-post-api");
//const social = new SocialPost(process.env.AYRSHARE_API_KEY);


let upload = storageFun(__dirname + '/../public/images/products');



/********* get products */
router.get("/home", function (req, res) {
    var cats_products = [];
    Category.find({}).exec(function (err, cats) {
        if (err) { console.log(err); return res.json({ message: "fail" }); }
        if (!cats.length) return res.render("home", { cats_products: [] });
        /*** */

        //check this if it works properly when using other categories
        var cat_count = 0;
        cats.forEach(async function (cat, i, arr) {
            Product.find({ Sub_item: { $in: cat.Sub_items } }).sort({ createdAt: -1 }).limit(4).exec(function (err, products) {
                if (err) {
                    console.log(err);
                    return res.json({ message: "fail" });
                }
                cat_count++;
                cats_products[cat.name] = products;
                cats_products[cat.name]._id = cat._id;
                if (cat_count === arr.length) {
                    //   console.log(cats_products["Components"][0]._id);
                    res.render("home", { cats_products });
                }
            })

        });
    })
});

//get product by id
router.get("/product/details/:id/:resType?", function (req, res) {
    Product.findOne({ _id: req.params.id }, function (err, product) {
        if (err) { console.log(err); return res.redirect("/home"); }
        if (req.params.resType == "json") { return res.json({ message: "success", product }); }
        res.render("product/product", { product })
    });
})

//get multiple products by ids
router.post("/ids/products", function (req, res) {
    Product.find({ _id: { $in: req.body.ids } }, function (err, products) {
        if (err) { console.log(err); return res.json({ message: "fail" }); }
        res.json({ message: "success", products });
    });
})

//get products by subcat
router.get("/category/:sub_category/products", function (req, res) {
    var sub_category = req.params.sub_category;

    Sub_item.findOne({ _id: sub_category }, function (err, sub_item) {
        if (err || !sub_item) {
            console.log(err);
            return res.json({ message: "fail" });
        }
        var searchkey = sub_item.name;
        Product.find({ Sub_item: sub_category }).populate("Sub_item").sort({ createdAt: -1 }).exec(function (err, products) {
            if (err) {
                console.log(err);
                return res.json({ message: "fail" });
            }
            else if (!products) return res.send("No Results");
            if (req.query.admin) {
                if (req.user?.role == "admin") return res.render("admin/products", { cat: sub_item, products, sub_item }); else
                    return res.redirect("/login");
            }
            res.render("product/products", { cat: sub_item, products, searchkey });

        });

    });

});

//get products by category
router.get("/category/:category_id/all/products", function (req, res) {
    Category.findOne({ _id: req.params.category_id }, function (err, cat) {
        if (err || !cat) { console.log(err); return res.json({ message: "fail in finding category" }) }
        Product.find({ Sub_item: { $in: cat.Sub_items } }).sort({ createdAt: -1 }).exec(function (errP, products) {
            if (errP) { console.log(err); return res.json({ message: "fail" }) };
            var searchkey = cat.name;
            res.render("product/products", { cat, products, searchkey });
        });
    })
});


//get products by category or subcategory pagination
router.get("/category/:category_id/:page_num", function (req, res) {
    //var last_date = req.query.last_date ? new Date(req.query.last_date).toISOString() : new Date().toISOString();
    var last_id = req.query.last_id;
    var limit = req.query.limit || 50;
    //var op=limit>0 ? 'lt' : 'gt';
    Category.findOne({ _id: req.params.category_id }, function (err, cat) {
        if (err || !cat) { console.log("fail in finding category", err); return res.redirect('/home'); }
        var query = {
            $or: [{ Sub_item: { $in: cat.Sub_items } }, { Sub_item: req.params.category_id }]
        };
        if (last_id) {
            if (limit > 0)
                query._id = { "$lt": last_id };
            else query._id = { "$gt": last_id };
        }
        Product.find(query).sort([['_id', -1]]).limit(parseInt(limit)).exec(function (errP, products) {
            if (errP) { console.log(err); return res.redirect('/home'); };
            var searchkey = cat.name;
            Product.count({ Sub_item: { $in: cat.Sub_items } }, function (err, count) {
                res.render("product/products", { cat, products, searchkey, page_number: req.params.page_num, cat_prod_count: count });
            })
        });
    });
});

//search products by name
router.get("/search/products/:productsName", function (req, res) {
    var productsName = req.params.productsName;
    var searchkey = productsName;

    Product.find({ name: { $regex: ".*" + productsName + ".*", $options: 'i' } }, function (err, products) {
        if (err) {
            console.log(err); return res.status(500).json({ message: "fail" });
        }
        else if (products.length == 0) return res.render("product/products", { cat: productsName, products, searchkey: "no results for " + searchkey });
        return res.render("product/products", { cat: productsName, products, searchkey });
    });

});



/******** adding product */
router.post("/new_product", upload.array('productImages', 10), function (req, res) {
    if (req.files) {
        var productName = req.body.productName;
        var subItem_id = req.body.subItem_id;
        var productDesc = req.body.productDesc;
        var description_blocks = req.body.description_blocks;
        var price = req.body.price;
        var in_stock = req.body.inStock == "on" ? true : false;
        var TTC = price * 1.2;
        Sub_item.findOne({ _id: subItem_id }, function (err, sub_item) {
            if (err || !sub_item) {
                console.log(err);
                return res.json({ message: "fail" });
            }
            //if category field is added in product find it by subitem and add it here
            Product.create({ name: productName, Sub_item: sub_item, description: productDesc, description_blocks, price, in_stock, TTC }, async function (err, product) {
                if (err) {
                    console.error(err); return res.json({ message: "fail" });
                }
                for (var i = 0; i < req.files.length; i++) {
                    const response = await file_manager.createFile(req.files[i].path, 'products');
                    response.original_path = req.files[i].path;
                    product.images.push(response);
                }
                product.save(async function () {
                    //await postToSocial(product);
                    return res.redirect("/category/" + subItem_id + "/products?admin=true");
                })
            });

        })

    }
    else {
        return res.json({ message: "fail", desc: "no image" });
    }

});

//not used for now: post to social media
async function postToSocial(product) {
    var message = product.name + " " + product.description + " "
        + product.price + "DH \u2063\n \u2063\n \u2063\n <div style='display:none'>";
    let images = product.images.map(image => image.secure_url);
    console.log(product.images);
    const post = await social.post({
        post: message,
        platforms: ["facebook", "instagram"],
        mediaUrls: [product.images[0][process.env.NODE_ENV == "production" ?
            process.env.DOMAIN_NAME + "/images/products/" + product.images[0].original_filename :
            product.images[0].secure_url]],
    }).catch(console.error);
    console.log(post);
}


//add email to product
router.post("/add/email_product/:product_id", function (req, res) {
    var email = req.body.email;
    Product.findOne({ _id: req.params.product_id }, function (err, product) {
        if (err || !product) { console.log(err); return res.json({ message: "fail" }); }
        if (!product.emails_availability) product.emails_availability = [];
        if (product.emails_availability.indexOf(email) > -1) {
            return res.json({ message: "fail", desc: "already exists" });
        }
        product.emails_availability.push(email);
        product.save(function () {
            return res.json({ message: "success", product });
        });
    });
});






module.exports = router;