const path = require('path');
const fs = require('fs');
const puppeteer = require('puppeteer');
const sharp = require('sharp');

const DIR = process.env.CARDS_PATH || '../cards';

async function genCards({ center, type, wayId, zoom, number, address }) {
    const browser = await puppeteer.launch({
        executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || '/usr/bin/chromium-browser',
        args: ['--no-sandbox', '--disable-setuid-sandbox']
    });


    let latlng = center && center.lat && center.lng ? `lat=${center.lat}&lng=${center.lng}&` : '';

    const page = await browser.newPage();
    await page.setViewport({ width: 1144, height: (750 + 140) })
    await page.goto(`https://sheep-service.com/screenshot.html?${latlng}type=${type}&wayId=${wayId}&zoom=${zoom}&address=${address}&number=${number}`, { timeout: 0 });
    await page.waitForSelector('.leaflet-tile-loaded', { timeout: 30000 });
    await new Promise(resolve => setTimeout(resolve, 1000));

    let name = () => {
        if (type == "house") return `T${number}.png`
        else if (type == "entrance") return `E${number}.png`
        else if (type == "homestead") return `H${number}.png`
        return `${Date.now()}.png`
    }

    if (!fs.existsSync(path.join(DIR, 'cache'))) {
        fs.mkdirSync(path.join(DIR, 'cache'), { recursive: true })
    }

    await page.screenshot({ path: path.join(DIR, "cache", name()) });

    await browser.close();

    return name();
}

async function saveCards({ center, type, wayId, zoom, number, address }) {
    let name = await genCards({ center, type, wayId, zoom, number, address });

    if (!fs.existsSync(path.join(DIR, type))) {
        fs.mkdirSync(path.join(DIR, type), { recursive: true });
    }

    try {
        const metadata = await sharp(path.join(DIR, 'cache', name)).metadata();
        const width = metadata.width;
        const height = metadata.height;

        if (width > 20 && height > 140) {
            const outputPath = path.join(DIR, type, name.replace(path.extname(name), '.webp'));

            await sharp(path.join(DIR, 'cache', name))
                .extract({
                    left: 0,
                    top: 0,
                    width: width,
                    height: height - 140
                })
                .webp()
                .toFile(outputPath);

            return fs.existsSync(outputPath);
        } else {
            console.error('Изображение слишком маленькое для обрезки!');
            return false;
        }
    } catch (err) {
        console.error('Ошибка при обработке изображения:', err);
        return false;
    }
}

module.exports = saveCards;