import {Response, Request} from 'express'
import FileService from '../service/FileService'
import base64ArrayBuffer from '../utils/base64ArrayBuffer.utils'
import * as fs from 'fs';
import * as path from "path";

export default class FileController{

    constructor(
        private fileService : FileService
    ) {}

    async getAll(req: Request, res: Response) {
        try{
            res.send(await this.fileService.getAll())
        } catch(error){
            return res.status(501).json({ error: error.toString() });
        }
        res.end()

    }

    async getById(req: Request, res: Response) {
        try{
            res.send(await this.fileService.get(req.params.id))
        } catch(error){
            return res.status(501).json({ error: error.toString() });
        }
        res.end()
    }

    async getBase64(req: Request, res: Response) {
        try{
            let file = await this.fileService.get(req.params.id)
            let p = path.resolve("./", file.path)
            res.set('content-type', 'text/plain')
            fs.readFile(p, (err, data) => res.send(base64ArrayBuffer(data)));
        } catch(error){
            return res.status(501).json({ error: error.toString() });
        }
        res.end()
    }

    async getContent(req: Request, res: Response) {
        try{
            let file = await this.fileService.get(req.params.id)
            let p = path.resolve("./", file.path)
            console.log(p)
            res.set('content-type', file.mimetype)
            fs.readFile(p, (err, data) => res.send(data));
        } catch(error){
            return res.status(501).json({ error: error.toString() });
        }
        res.end()
    }

    async create(req: Request, res: Response) {
        try{
            res.send(await this.fileService.create(req.file))
        } catch(error){
            return res.status(501).json({ error: error.toString() });
        }
        res.end()
    }

    async update(req: Request, res: Response) {
        try{
            //req.send(await this.imageService.update())
        } catch(error){
            return res.status(501).json({ error: error.toString() });
        }
        res.end()
    }

    async delete(req: Request, res: Response) {
        try{
            let file = await this.fileService.get(req.params.id)
            res.send(await this.fileService.delete(req.params.id))
            let p = path.resolve("./", file.path)
            fs.unlinkSync(p)
        } catch(error){
            return res.status(501).json({ error: error.toString() });
        }
        res.end()
    }
}
