const upload = require("../middlewares/upload");
const dbConfig = require("../config/db.config");
const MongoClient = require("mongodb").MongoClient;
const GridFSBucket = require("mongodb").GridFSBucket;
const url = dbConfig.url;
const baseUrl = dbConfig.fileUrl;
const mongoClient = new MongoClient(url);
const uploadFiles = async (req, res) => {
  try {
    await upload(req, res);
    if (req.file == undefined) {
      return res.send({
        message: "You must select a file.",
      });
    }
    return res.send({
      message: "File has been uploaded.",
    });
  } catch (error) {
    console.log(error);
    return res.send({
      message: "Error when trying upload image: ${error}",
    });
  }
};
const getFile = async (req, res) => {
  try {
    await mongoClient.connect();
    const database = mongoClient.db(dbConfig.database);
    const images = database.collection(dbConfig.imgBucket + ".files");
    const chunks = database.collection(dbConfig.imgBucket + ".chunks");
    const cursor = await (images.find({filename: req.params.name}).toArray());
    if (cursor.length === 0) {
      return res.status(500).send({
        message: "No files found!",
      });
    }
    const chunkCursor = await(chunks.find({files_id: cursor[cursor.length-1]._id}).toArray());
    return res.status(200).send(chunkCursor[0].data);
  } catch (error) {
    return res.status(500).send({
      message: error.message,
    });
  }
};

const deleteFile = async (req, res) => {
  try {
    await mongoClient.connect();
    const database = mongoClient.db(dbConfig.database);
    const images = database.collection(dbConfig.imgBucket + ".files");
    const chunks = database.collection(dbConfig.imgBucket + ".chunks");
    const cursor = await (images.find({filename: req.body.name}).toArray());
    if (cursor.length > 0) {
      await chunks.deleteMany({files_id: cursor[cursor.length-1]._id});
      await images.deleteMany({filename: req.body.name});
    }
    return res.status(200).send({ message: 'Delete Image Succeed'});
  } catch (error) {
    return res.status(500).send({
      message: error.message,
    });
  }
};

module.exports = {
  uploadFiles,
  getFile,
  deleteFile
};