const multer = require('multer');
const { zip } = require('zip-a-folder');
const path = require('path');
const fs = require('fs-extra');

const Minute = require('../../models/minutes/minutes');
module.exports = {
    readContent: async (req, res, next) => {
        try {
            let { minuteid } = req.params;
            if (!minuteid) return res.status(401).json({ message: '缺少會議ID' });

            const minuteData = await Minute.get(minuteid);
            const { MEETING_TITLE: title, MEETING_DOC_NAME: fileName } = minuteData[0];

            let filePath = path.join(__dirname + `../../../minutesFiles/${title}/${fileName}`);
            const data = fs.readFileSync(filePath);
            res.contentType('application/pdf');
            res.send(data);
        } catch (err) {
            res.status(500).json(err);
        }
    },
    getFolderFiles: async (req, res, next) => {
        try {
            let { title: folderName } = req.query;
            if (!folderName) return res.status(401).json({ message: '缺少資料夾名稱' });
            const dirname = path.join(__dirname + `../../../minutesFiles/${folderName}`);
            const filenames = fs.readdirSync(dirname);
            const filesArr = [];
            filenames.map((filename) => {
                if (filename !== '附件' && filename.indexOf('.zip') < 0) filesArr.push({ content: filename });
                else {
                    const dirnameWithAttach = path.join(__dirname + `../../../minutesFiles/${folderName}/附件`);
                    const attachFilesname = fs.readdirSync(dirnameWithAttach);
                    attachFilesname.map((attach) => {
                        filesArr.push(attach);
                    });
                }
            });
            res.status(200).json(filesArr);
        } catch (err) {
            res.status(500).json(err);
        }
    },
    delete: (req, res, next) => {
        try {
            let { folderName, fileName } = req.body;
            if (!folderName || !fileName) return res.status(401).json({ message: '缺少資料夾或檔案名稱' });
            const dirname = path.join(__dirname + `../../../minutesFiles/${folderName}`);

            if (fs.existsSync(dirname + `/${fileName}`)) {
                fs.unlinkSync(dirname + `/${fileName}`);
            } else {
                fs.unlinkSync(dirname + `/附件/${fileName}`);
            }
            res.status(200).json({ message: '刪除成功' });
        } catch (err) {
            res.status(500).json(err);
        }
    },
    download: async (req, res, next) => {
        try {
            const { folder, file } = req.query;
            if (!folder && !file) return res.status(401).json({ message: '缺少資料夾和檔案名稱' });
            //判斷下載的是壓縮檔或普通檔案
            let filePath = file
                ? path.join(__dirname + `../../../minutesFiles/${folder}/${file}`)
                : path.join(__dirname + `../../../minutesFiles/會議記錄壓縮檔/${folder}.zip`);

            if (fs.existsSync(filePath)) {
                res.download(filePath);
            } else {
                filePath = path.join(__dirname + `../../../minutesFiles/${folder}/附件/${file}`);
                if (fs.existsSync(filePath)) res.download(filePath);
                else {
                    res.status(404).json({ message: '無法存取該檔案' });
                }
            }
        } catch (err) {
            res.status(500).json(err);
        }
    },
    compress: async (req, res, next) => {
        try {
            const { folder } = req.query;
            if (!folder) return res.status(401).json({ message: '缺少資料夾名稱' });
            const filePath = path.join(__dirname + `../../../minutesFiles/${folder}`);
            let zipPath = path.join(__dirname + `../../../minutesFiles/會議記錄壓縮檔/`);
            if (fs.existsSync(filePath)) {
                if (!fs.existsSync(zipPath)) fs.mkdirSync(zipPath);
                zipPath += `${folder}.zip`;
                if (!fs.existsSync(zipPath)) {
                    await zip(filePath, zipPath);
                }
                return next();
            } else {
                return res.status(404).json({ message: '無法存取該檔案' });
            }
        } catch (err) {
            res.status(500).json(err);
        }
    },
    getFolder: (folderName) => {
        try {
            const dirname = path.join(__dirname + `../../../minutesFiles/${folderName}`);
            if (!fs.existsSync(dirname)) return;
            const filenames = fs.readdirSync(dirname);
            const filesArr = [];
            filenames.map((filename) => {
                if (filename !== '附件') filesArr.push(filename);
                else {
                    const dirnameWithAttach = path.join(__dirname + `../../../minutesFiles/${folderName}/附件`);
                    const attachFilesname = fs.readdirSync(dirnameWithAttach);
                    attachFilesname.map((attach) => {
                        filesArr.push(attach);
                    });
                }
            });
            return { folder: folderName, files: filesArr };
        } catch (err) {
            return err;
        }
    },
    upload: multer({
        storage: multer.diskStorage({
            destination: (req, file, cb) => {
                //以會議標題為資料夾名稱
                let folderName = req.body.folderName ? req.body.folderName : req.body.title;
                let dir = `./minutesFiles/${folderName}`;
                //刪除路徑空格及格式化
                dir = dir.replace(/\s/g, '');
                dir = path.normalize(dir).replace(/^(\.\.(\/|\\|$))+/, '');
                //判斷資料夾是否存在，如果無則創建
                if (!fs.existsSync(dir)) fs.mkdirSync(dir);
                if (!fs.existsSync(dir + '/附件')) fs.mkdirSync(dir + '/附件');

                if (file.fieldname == 'content') return cb(null, dir);
                if (file.fieldname == 'attach') return cb(null, dir + '/附件');
            },
            filename: (req, file, cb) => {
                cb(null, file.originalname);
            },
        }),
    }),
};
