const jwt = require("jsonwebtoken");
const { promisify } = require("util");
const Products = require("../models/productsModel");
const User = require("../models/userModel");
const moment = require("moment/moment");
const sharp = require("sharp");
const fs = require("fs");
const writeFileAsync = promisify(fs.writeFile);

const verification = async (token) => {
  try {
    // if (token.startsWith("Bearer ")) {
    //   TokenArray = token.split(" ");
    //   const decoded = jwt.verify(TokenArray[1], process.env.JWT_SECRET);
    //   const user = await User.findOne({ _id: decoded.id });
    //   if (user !== null && decoded.exp > Date.now() / 1000) {
    //     return true;
    //   } else {
    //     return false;
    //   }
    // } else {
    //   return false;
    // }
    return true;
  } catch (error) {
    return false;
  }
};

exports.getProducts = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const products = await Products.find({ IsDelete: false });
    res.setHeader("Content-Type", "application/javascript");
    res.status(200).send({
      message: "",
      IsSuccess: true,
      Status_Code: 200,
      Data: products,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.getProductsDropdown = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const products = await Products.find(
      { IsDelete: false }, // Query criteria
      { name: 1, _id: 1, price: 1 } // Projection to include only name and _id fields
    );
    res.setHeader("Content-Type", "application/javascript");
    res.status(200).send({
      message: "",
      IsSuccess: true,
      Status_Code: 200,
      Data: products,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.getProductsById = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const productID = req.params.id;
    const product = await Products.findById(productID);
    res.setHeader("Content-Type", "application/javascript");
    res.status(200).send({
      message: "",
      IsSuccess: true,
      Status_Code: 200,
      Data: product,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.saveProduct = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const body = req.body;
    const imagesArray = [];
    //Save Images
    if (req.body.images && req.body.images.length > 0) {
      for (let i = 0; i < req.body.images.length; i++) {
        const imageData = req.body.images[i];
        if (imageData !== null) {
          var base64Data = imageData.File.replace(
            /^data:image\/(png|jpeg|jpg);base64,/,
            ""
          );

          const buffer = Buffer.from(base64Data, "base64");

          // Resize the image to 600x400 pixels using sharp
          const resizedImage = await sharp(buffer).resize(600, 400).toBuffer();

          try {
            await writeFileAsync(
              `assets/uploads/products/${body.name.replace(" ", "_")}_${
                i + 1
              }.jpeg`,
              resizedImage
            );
            imagesArray.push(
              // http://85.239.232.188:
              `http://85.239.232.188:${
                process.env.PORT
              }/assets/uploads/products/${body.name.replace(" ", "_")}_${
                i + 1
              }.jpeg`
              // `${req.protocol}://${req.hostname}:${
              //   process.env.PORT
              // }/assets/uploads/products/${body.name.replace(" ", "_")}_${
              //   i + 1
              // }.jpeg`
            );
            console.log("Image saved successfully.");
          } catch (err) {
            console.error("Error writing the file:", err);
          }
        }
      }
    }
    console.log(imagesArray);
    const data = {
      name: body.name,
      description: body.description,
      price: body.price,
      tickets: body.tickets,
      imageURL: req.body.images !== null ? imagesArray : [],
      IsActive: body.IsActive,
      IsDelete: false,
      CreatedBy: body.User,
      CreatedOn: moment().format("YYYY-MMM-DD"),
    };
    const newProduct = await Products.create(data);
    res.json({
      message: "New Product created successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: newProduct,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.editProduct = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const body = req.body;
    const imagesArray = [];

    if (req.body.images !== null && req.body.images.length > 0) {
      for (let i = 0; i < req.body.images.length; i++) {
        const imageData = req.body.images[i];
        if (imageData !== null) {
          var base64Data = imageData.File.replace(
            /^data:image\/(png|jpeg|jpg);base64,/,
            ""
          );

          const buffer = Buffer.from(base64Data, "base64");

          // Resize the image to 600x400 pixels using sharp
          const resizedImage = await sharp(buffer).resize(600, 400).toBuffer();

          try {
            await writeFileAsync(
              `assets/uploads/products/${body.name.replace(" ", "_")}_${
                i + 1
              }.jpeg`,
              resizedImage
            );
            imagesArray.push(
              `http://85.239.232.188:${
                process.env.PORT
              }/assets/uploads/products/${body.name.replace(" ", "_")}_${
                i + 1
              }.jpeg`
              // `${req.protocol}://${req.hostname}:${
              //   process.env.PORT
              // }/assets/uploads/products/${body.name.replace(" ", "_")}_${
              //   i + 1
              // }.jpeg`
            );
            console.log("Image saved successfully.");
          } catch (err) {
            console.error("Error writing the file:", err);
          }
        }
      }
      const updateProduct = await Products.updateOne(
        { _id: body._id },
        {
          $set: {
            name: body.name,
            description: body.description,
            price: body.price,
            tickets: body.tickets,
            imageURL: imagesArray,
            IsActive: body.IsActive,
            ModifiedBy: body.User,
            ModifiedOn: moment().format("YYYY-MMM-DD"),
          },
        }
      );
    } else {
      const updateProduct = await Products.updateOne(
        { _id: body._id },
        {
          $set: {
            name: body.name,
            description: body.description,
            price: body.price,
            tickets: body.tickets,
            IsActive: body.IsActive,
            ModifiedBy: body.User,
            ModifiedOn: moment().format("YYYY-MMM-DD"),
          },
        }
      );
    }

    const updatedProduct = await Products.findById(body._id);
    res.json({
      message: "Product updated successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: updatedProduct,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.deleteProduct = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const body = req.body;
    const updateProduct = await Products.updateOne(
      { _id: body._id },
      {
        $set: {
          IsActive: body.IsActive,
          IsDelete: body.IsDelete,
          ModifiedBy: body.User,
          ModifiedOn: moment().format("YYYY-MMM-DD"),
        },
      }
    );
    const updatedProduct = await Products.findOne({
      _id: body._id,
    });
    res.json({
      message: "Product deleted successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: updatedProduct,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};
