const jwt = require("jsonwebtoken");
const { promisify } = require("util");
const HomeBanner = require("../models/homeBanner");
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.getHomeBanner = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const homeBanner = await HomeBanner.find();

    res.setHeader("Content-Type", "application/javascript");
    res.status(200).send({
      message: "",
      IsSuccess: true,
      Status_Code: 200,
      Data: homeBanner,
    });
  } 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.saveHomeBanner = 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(342, 192).toBuffer();

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