import { render } from 'ejs';
import { readFileSync, existsSync, mkdir } from 'fs';
import puppeteer from 'puppeteer';
import { randomUUID } from 'crypto';
import { join } from 'path';
import { visit_template } from '../templates/visit_template';
import { ServerConstants } from 'src/constants/server.contants';

export class VisitedPlacesImageCreator {
    public async generateImage(imagesURL: string[]) {
        try {
            const template = this.getTemplate(imagesURL);
            const browser = await puppeteer.launch();
            const page = await browser.newPage();
            await page.setContent(template);
            await page.setViewport({ width: 470, height: 320, deviceScaleFactor: 2 });
            const outDir = join(__dirname, "../../../static/visits");
            if (!existsSync(outDir)) {
                mkdir(outDir, { recursive: true }, (err) => {
                    if (err) throw err;
                });
            }
            const imageName = `${randomUUID()}.png`;
            const outPath = join(outDir, imageName);
            await page.screenshot({ path: outPath });
            await browser.close();

            return join(ServerConstants.HOST, "visits", imageName);
            
        } catch (error) {
            console.log(error);
            throw error;
        }
    }

    private getTemplate(images: string[]) {
        const template = visit_template(images);
        return render(template, { images });
    }
}