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

const { FileSearch } = mapnik();

const maxLimit = 100;

// example: GET /api/gis-files?dir=tiles/3828667893214610450/13/4884&key=1&size=1675&period=5m
export default async function fileSearch({
    query,
}, reply) {
    if (!FileSearch) {
        return reply.status(400).send({ error: 'mapnik server address needed', code: 400 });
    }

    const {
        dir, key, period, size, page,
    } = query;

    const limit = Math.min(query.limit || 16, maxLimit);
    const offset = page && page > 0 ? (page - 1) * limit : 0;

    if (!key && !period && !size) {
        return reply.status(400).send({ error: 'not enough query params: key / period / size', code: 400 });
    }

    const result = await FileSearch({
        path: dir, key, period, size,
    });

    return {
        count: result.count,
        data: (result.files || []).slice(offset, offset + limit).map(el => ({ type: 'file', ...el })),
    };
}
