const jwt = require("jsonwebtoken");
const { promisify } = require("util");
const Winners = require("../models/winnersModel");
const Campaigns = require("../models/campaignsModel");
const Prize = require("../models/prizeModel");
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.getWinners = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const winners = await Winners.find({ IsDelete: false });

    // Map each campaign to a promise that resolves with the modified campaign data
    const winnersWithDetails = await Promise.all(
      winners.map(async (item) => {
        const campaign = await Campaigns.findById(item.campaignId);
        const prize = await Prize.findById(campaign.prizeId);
        return {
          ...item._doc,
          campaignName: campaign ? campaign.name : null,
          prizeAmount: prize ? prize.amount : null,
        };
      })
    );

    res.setHeader("Content-Type", "application/javascript");
    res.status(200).send({
      message: "",
      IsSuccess: true,
      Status_Code: 200,
      Data: winnersWithDetails,
    });
  } 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.saveWinner = 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/winners/${body.name.replace(" ", "_")}_${
                i + 1
              }.jpeg`,
              resizedImage
            );
            imagesArray.push(
              // http://85.239.232.188:
              `http://85.239.232.188:${
                process.env.PORT
              }/assets/uploads/winners/${body.name.replace(" ", "_")}_${
                i + 1
              }.jpeg`
              // `${req.protocol}://${req.hostname}:${
              //   process.env.PORT
              // }/assets/uploads/winners/${body.name.replace(" ", "_")}_${
              //   i + 1
              // }.jpeg`
            );
            console.log("Image saved successfully.");
          } catch (err) {
            console.error("Error writing the file:", err);
          }
        }
      }
    }
    const data = {
      name: body.name,
      campaignId: body.campaignId,
      announcedOn: body.announcedOn,
      imageURL: req.body.images !== null ? imagesArray : [],
      IsActive: body.IsActive,
      IsDelete: false,
      CreatedBy: body.User,
      CreatedOn: moment().format("YYYY-MMM-DD"),
    };
    const newWinner = await Winners.create(data);

    // Map each campaign to a promise that resolves with the modified campaign data
    const campaign = await Campaigns.findById(newWinner.campaignId);
    const newData = {
      ...newWinner._doc,
      campaignName: campaign ? campaign.name : null,
    };
    res.json({
      message: "New Winner created successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: newData,
    });
  } 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.editWinner = 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/winners/${body.name.replace(" ", "_")}_${
                i + 1
              }.jpeg`,
              resizedImage
            );
            imagesArray.push(
              // http://85.239.232.188:
              `http://85.239.232.188:${
                process.env.PORT
              }/assets/uploads/winners/${body.name.replace(" ", "_")}_${
                i + 1
              }.jpeg`
              // `${req.protocol}://${req.hostname}:${
              //   process.env.PORT
              // }/assets/uploads/winners/${body.name.replace(" ", "_")}_${
              //   i + 1
              // }.jpeg`
            );
            console.log("Image saved successfully.");
          } catch (err) {
            console.error("Error writing the file:", err);
          }
        }
      }
      const updateWinner = await Winners.updateOne(
        { _id: body._id },
        {
          $set: {
            name: body.name,
            campaignId: body.campaignId,
            announcedOn: body.announcedOn,
            imageURL: imagesArray,
            IsActive: body.IsActive,
            ModifiedBy: body.User,
            ModifiedOn: moment().format("YYYY-MMM-DD"),
          },
        }
      );
    } else {
      const updateWinner = await Winners.updateOne(
        { _id: body._id },
        {
          $set: {
            name: body.name,
            campaignId: body.campaignId,
            announcedOn: body.announcedOn,
            IsActive: body.IsActive,
            ModifiedBy: body.User,
            ModifiedOn: moment().format("YYYY-MMM-DD"),
          },
        }
      );
    }
    const updatedWinner = await Winners.find({ _id: body._id });
    // Map each campaign to a promise that resolves with the modified campaign data
    const winnersWithDetails = await Promise.all(
      updatedWinner.map(async (item) => {
        const campaign = await Campaigns.findById(item.campaignId);
        return {
          ...item._doc,
          campaignName: campaign ? campaign.name : null,
        };
      })
    );
    res.json({
      message: "Winner updated successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: winnersWithDetails[0],
    });
  } 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.deleteWinner = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const body = req.body;
    const updateWinner = await Winners.updateOne(
      { _id: body._id },
      {
        $set: {
          IsActive: body.IsActive,
          IsDelete: body.IsDelete,
          ModifiedBy: body.User,
          ModifiedOn: moment().format("YYYY-MMM-DD"),
        },
      }
    );
    const updatedWinner = await Winners.findOne({
      _id: body._id,
    });
    res.json({
      message: "Winner deleted successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: updatedWinner,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};
