const bcrypt = require("bcryptjs");
const _ = require("lodash");
const express = require("express");
const { UserResponses } = require("../../models/UserResponses");
const { Guest } = require("../../models/Guest");
const router = express.Router();
const emailTransport = require("../api/helpers/emailTransport");
const { Company } = require("../../models/Company");
const PDFDocument = require("pdfkit");
const fs = require("fs");
const os = require("os");
const path = require("path");
const config = require("config");
const http = require("http");
const https = require("https");
// const axios = require("axios");

const AWS = require("aws-sdk");
// import fetch from "node-fetch";

const { v1: uuidv1 } = require("uuid");

const s3 = new AWS.S3({
  accessKeyId: config.get("AWSaccessKeyId"),
  secretAccessKey: config.get("AWSsecretAccessKey"),
  region: config.get("AWSregion"),
  signatureVersion: "v4",
});

module.exports.add = async (req, res) => {
  try {
    // console.log("REQ BODY: ", req.body);
    const { customerId, responses, testResult, testGraph } = req.body;
    let result = new UserResponses({
      guest: customerId,
      responses,
      user: req.user._id,
      testResult,
      testGraph,
    });
    result = await result.save();
    result = await UserResponses.findById(result._id)
      .populate("guest")
      .populate("responses.question", "question");
    // let result = await UserResponses.findById("6308f86e29b7c5683eeb62ee")
    //   .populate("guest")
    //   .populate("responses.question", "question");

    let qa = "";
    result = JSON.parse(JSON.stringify(result));
    // console.log("RESULT: ", result);
    console.log("RESULT: ", result.responses.length);

    let company = await Company.findById(req?.user?.company);
    console.log("Company: ", company?.name, company.email);
    let pathpdf = await createPdfWithImageFromUrl(testGraph);
    // if (result.responses && result.responses.length > 0) {
    if (company) {
      for (let i = 0; i < result.responses.length; i++) {
        console.log("IN", qa);
        let quest = result?.responses[i];
        qa = qa + `<p><b>Q: ${quest?.question?.question}</b></p>`;
        qa = qa + `<p>Ans: ${quest?.answer}</p>`;
      }
      // }
      // console.log("QA: ", qa);
      const theHTML = `
        <div>
         Hello ${result?.guest?.firstName} ${result?.guest?.lastName},<br/>
         We are glad to have you!<br/>
         <br/>
          <p>Your hearing test result is attached.</p>
          <br/>
          ${qa}
          </div>
          <br/>
          Thanks.
          `;

      const filePath = path.join(__dirname, "../../output.pdf");
      var mailOptions = {
        from: { name: `Istar`, address: "istar@gmail.com" },
        // to: "muqbausman@gmail.com",
        to: company?.email,
        subject: "Hearing Test Result",
        attachments: [
          {
            filename: "graph.pdf",
            path: filePath,
            // path: "../../output.pdf",
            contentType: "application/pdf",
            // path: "https://istar-bucket.s3.ap-southeast-2.amazonaws.com/istar/fa924aa0-a75a-11ed-ae00-f345c49fc5c0IHS-Logo-Final-pink-small2.png",
          },
        ],
        html: theHTML,
      };
      // console.log("MAIL OPTION FROM", mailOptions.from);
      try {
        await emailTransport({ mailOptions });
        return res.status(200).send({
          message: "Result successfully forwarded to respective email!",
        });
      } catch (error) {
        return res
          .status(400)
          .send({ message: "Email don't work on this server yet " });
      }
    }

    return res.status(200).send({ message: "Response Submitted!" });
  } catch (err) {
    console.error(err);
    return res.status(400).send({ error: err.message });
  }
};

module.exports.addFR = async (req, res) => {
  try {
    console.log("REQ BODY: ", req.body);
    const { customerId, responses, testResult, companyId, testGraph } =
      req.body;
    let userResponse = new UserResponses({
      guest: customerId,
      responses,
      company: companyId,
      testResult,
      testGraph,
    });
    userResponse = await userResponse.save();
    userResponse = await UserResponses.findById(userResponse._id)
      .populate("guest")
      .populate("responses.question", "question");
    return res.status(200).send(userResponse);
  } catch (err) {
    console.error(err);
    return res.status(400).send({ error: err.message });
  }
};

module.exports.getSingle = async (req, res) => {
  try {
    const record = await UserResponses.findById(req.params.id);
    if (!record) throw Error("The record with the given ID was not found.");
    return res.send(record);
  } catch (err) {
    console.error(err);
    return res.status(404).send({ error: err.message });
  }
};

module.exports.delete = async (req, res) => {
  try {
    const record = await UserResponses.findByIdAndRemove(req.params.id);
    if (!record) throw Error("The record with the given ID was not found.");
    return res.send(record);
  } catch (err) {
    console.error(err);
    return res.status(404).send({ error: err.message });
  }
};

module.exports.update = async (req, res) => {
  try {
    let record = await UserResponses.findById(req.params.id);
    if (!record) throw Error("The record with the given ID was not found.");

    record = await UserResponses.findByIdAndUpdate(req.params.id, req.body);
    res.send(record);
  } catch (err) {
    console.error(err);
    return res.status(400).send({ error: err.message });
  }
};

module.exports.all = async (req, res) => {
  try {
    let drivers = await UserResponses.find({ user: req.user._id });
    return res.status(200).send(drivers);
  } catch (err) {
    console.log(err);
    return res.status(400).send({ error: err.message });
  }
};

module.exports.query = async (req, res) => {
  try {
    let query = req.body.query;
    query = query ? query : {};
    query.page = query.page ? query.page : 0;
    query.pageSize = query.pageSize ? query.pageSize : 10;
    let conditions = {};
    if (query.search) {
      conditions.$and = [
        {
          $or: [{ name: { $regex: new RegExp(query.search, "i") } }],
        },
      ];
    }
    let skip = query.page * query.pageSize;
    let sort = {};
    if (query.orderBy) {
      sort[query.orderBy.field] = query.orderDirection == "asc" ? 1 : -1;
    } else {
      sort.createdAt = 1;
    }
    const records = await UserResponses.find(conditions)
      .skip(skip)
      .sort(sort)
      .limit(query.pageSize);

    let total = await UserResponses.countDocuments(conditions);
    // total = Math.ceil(total / query.pageSize);
    res.send({ data: records, page: query.page, total });
  } catch (err) {
    console.error(err);
    return res.status(400).send({ error: err.message });
  }
};

module.exports.customerResponses = async (req, res) => {
  try {
    const { guestId } = req.body;
    const record = await UserResponses.findOne({ guest: guestId })
      .populate("responses.question", "question")
      .populate("guest", "firstName lastName");

    if (!record)
      throw Error("The record for the given customer was not found.");
    return res.send(record);
  } catch (err) {
    console.error(err);
    return res.status(401).send({ error: err.message });
  }
};

// "https://istar-bucket.s3.ap-southeast-2.amazonaws.com/istar/fa924aa0-a75a-11ed-ae00-f345c49fc5c0IHS-Logo-Final-pink-small2.png";

function sendFileToS3({ fileName }) {
  return new Promise((resolve, reject) => {
    // console.log("fileName::::", fileName, filePath);
    const homeDir = os.homedir();
    // const filePath = `../../ouput.pdf`;

    fs.readFile("output.pdf", "utf8", (err, fileContent) => {
      if (err) {
        console.error(err);
        return;
      }
      console.log(fileContent);
      s3.upload(
        {
          Bucket: config.get("AWSBucket"),
          Key: fileName,
          Body: fileContent,
        },
        (err, data) => {
          if (err) {
            console.log("ERRRRRR: ", err);
            reject(err);
          } else {
            console.log("DATA:", data);
            resolve(data.Location);
          }
        }
      );
    });
    // const fileContent = fs.readFileSync(filePath);
    // console.log("fileContent:", fileContent);
    // s3.upload(
    //   {
    //     Bucket: config.get("AWSBucket"),
    //     Key: fileName,
    //     Body: fileContent,
    //   },
    //   (err, data) => {
    //     if (err) {
    //       console.log("ERRRRRR: ", err);
    //       reject(err);
    //     } else {
    //       fs.unlinkSync(filePath);
    //       console.log("DATA:", data);
    //       resolve(data.Location);
    //     }
    //   }
    // );
  });
}

function createPdfWithImageFromUrl(imageUrl) {
  return new Promise(async (resolve, reject) => {
    try {
      const doc = new PDFDocument();
      doc.pipe(fs.createWriteStream("output.pdf"));

      // const imageBytes = await fetch(imageUrl).then((res) => res.arrayBuffer());
      // // const imageBytes = await axios
      // //   .get(imageUrl)
      // //   .then((res) => res.data.arrayBuffer());

      // doc.image(imageBytes, {
      //   fit: [250, 250],
      //   align: "center",
      //   valign: "center",
      // });

      // doc.end();

      // console.log("PDF file written to disk");
      // resolve();

      const requester = imageUrl.startsWith("https") ? https : http;

      requester
        .get(imageUrl, (response) => {
          const chunks = [];
          response.on("data", (chunk) => {
            chunks.push(chunk);
          });
          response.on("end", () => {
            const imageBytes = Buffer.concat(chunks);
            doc.image(imageBytes, {
              fit: [600, 600],
              align: "center",
              valign: "center",
            });
            doc.end();
            console.log("PDF file written to disk");
            resolve();
          });
        })
        .on("error", (err) => {
          console.error(err);
          resolve();
        });
    } catch (err) {
      console.error(err);
      resolve();
    }
  });
}
