import Sphericalmercator from '@mapbox/sphericalmercator';

import { config, logger, pgClients } from '@opengis/fastify-table/utils.js';

import mapnik from '../../../plugins/mapnik/funcs/mapnik.js';

const { RenderTile } = mapnik();

const mercator = new Sphericalmercator({ size: 256 });

/**
 * Формування растрового tile cartoCss
 *
 * @method GET
 * @alias rtile
 * @param {String} bbox - bbox
 * @param {Number} height - висота по координатам
 * @param {Number} width - ширина по координатам
 * @param {String} data - стилізація
 * @param {String} lang - мова
 * @param {String} z - координата z
 * @param {String} x - координата y
 * @param {String} y - координата x
 */

export default async function rtileMBD({
    pg = pgClients.client, params, query,
}, reply) {
    if (!RenderTile) {
        return reply.status(400).send({ error: 'mapnik server address needed', code: 400 });
    }

    const { id, z, y } = params;

    const x = params.x.split('.')[0] - 0;

    if (!id) {
        return reply.status(400).send({ error: 'not enough params: id', code: 400 });
    }

    if (!x || !y || !z) {
        return reply.status(400).send({ error: 'not enough params: xyz', code: 400 });
    }

    const mbd = pg.pk?.['data_mbd.mbd_existent_detail'] ? await pg.query(`
        select
            mbd_existent_detail_id as id, 
            upfile
        from data_mbd.mbd_existent_detail a
        left join data_mbd.mbd b on a.mbd_id=b.mbd_id
        where   material_type_id = '3245363247443870877'
        and     upfile is not null
        and     upfile ~ '.tif'
        and mbd_existent_detail_id=$1
    `, [id]).then(el => el.rows?.[0]) : [];

    if (!mbd) {
        return reply.status(404).send({ error: 'mbd not found', code: 404 });
    }

    const bbox = mercator.bbox(y, x, z, false, '900913');

    try {
        const data = await RenderTile({
            path: mbd.upfile,
            name: id,
            width: 256,
            height: 256,
            bbox,
            ttl: query.nocache ? '0' : '1h',
            debug: query.debug,
        });

        if (query.debug) {
            return data;
        }

        if (data.err) {
            logger.file('rtile/mbd/error', { error: data.err });
            return reply.status(500).send({ error: config.local ? data.err : 'render error', code: 500 });
        }

        const buffer = Buffer.from(data.base64, 'base64');

        return reply.headers({ 'Content-Type': 'image/png' }).send(buffer);
    }
    catch (err) {
        logger.file('rtile/mbd/error', { error: err.toString(), stack: err.stack });
        return reply.status(500).send({ error: config.local ? err.toString() : 'rtile error', code: 500 });
    }
}
