import {Response, Request} from 'express'
import CardService from '../service/CardService'
import FileService  from '../service/FileService'
import path from "path";
import fs from "fs";

export default class CardController {
    getImage: any;

    constructor(
        private cardService : CardService,
        private fileService : FileService
    ) {}

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

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

    async getFrontImage(req: Request, res: Response) {
        try{
            let card = await this.cardService.get(req.params.id);
            // @ts-ignore
            let file = await this.fileService.get(card._doc.frontImage)
            let p = path.resolve("./", file.path)
            res.set('content-type', file.contenttype)
            await fs.readFile(p, (err, data) => res.send(data));
            } catch(error){
            return res.status(501).json({ error: error.toString() });
        }
    }

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

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

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

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