const path = require("path");
const fs = require("fs");
const sharp = require("sharp");
const formidable = require("formidable");

// filesize counter
const sizeCounter = (arr) => {
  let obj = [];
  let size = 0;

  arr.map((d) => {
    let s = fs.statSync(
      path.join(__dirname, "../uploads/files/" + d.file_name)
    );
    obj.push({ ...d._doc, size: s.size });
    size += s.size;
  });
  return {
    sizedFiles: obj,
    total_size: size,
  };
};

// delete file
const delete_file = async (req, res) => {
  try {
    const { filename, isImage } = req.body;
    let file;
    if (isImage) {
      file = path.join(__dirname, "../uploads/images/" + filename);
    } else {
      file = path.join(__dirname, "../uploads/" + filename);
    }
    // console.log({ file, filename });
    fs.unlinkSync(file);
    res.status(200).json({ success: true, message: `deleted.` });
  } catch (error) {
    console.log(error);
    res
      .status(500)
      .json({ success: false, message: "Could not delete the file" });
  }
};

// upload resized images
const fileUploadResized = async (req, res) => {
  const form = new formidable.IncomingForm();
  form.parse(req, async (err, fields, files) => {
    if (err) {
      console.error(err);
      return res.status(500).send({ message: "Error receiving file!" });
    }

    const receivedFile = files.files[0];
    // console.log({ receivedFile });
    try {
      const path = `./uploads/images/${new Date().getTime()}___${
        receivedFile.originalFilename
      }`;

      const img = await sharp(receivedFile.filepath)
        .resize(600, 600)
        .toFile(path);

      return res
        .status(201)
        .json({ success: true, message: "image uploaded", data: img, path });
    } catch (error) {
      console.error(error);
      return res.status(500).send({ message: "Error processing file!" });
    }
  });
};

// upload resized images
const fileUploadResizedAvatar = async (req, res) => {
  const form = new formidable.IncomingForm();
  form.parse(req, async (err, fields, files) => {
    if (err) {
      console.error(err);
      return res.status(500).send({ message: "Error receiving file!" });
    }

    const receivedFile = files.files[0];
    // console.log({ receivedFile });
    try {
      const avatarPath = `./uploads/avatars/${new Date().getTime()}___${
        receivedFile.originalFilename
      }`;

      const img = await sharp(receivedFile.filepath)
        .resize(600, 600)
        .toFile(avatarPath);

      return res.status(201).json({
        success: true,
        message: "image uploaded",
        data: img,
        avatarPath,
      });
    } catch (error) {
      console.error(error);
      return res.status(500).send({ message: "Error processing file!" });
    }
  });
};

// delete avatar file
const delete_avatar = async (req, res) => {
  try {
    const { filename } = req.body;
    let file = path.join(__dirname, "../uploads/avatars/" + filename);

    // console.log({ file });
    fs.unlinkSync(file);
    res.status(200).json({ success: true, message: `deleted.` });
  } catch (error) {
    console.log(error);
    res
      .status(500)
      .json({ success: false, message: "Could not delete the avatar file" });
  }
};

module.exports = {
  delete_file,
  fileUploadResized,
  fileUploadResizedAvatar,
  delete_avatar,
};
