import { dataUpdate, getMeta, getSelectVal, yml2json } from "@opengis/fastify-table/utils.js";

export default async function legendAuto({ params = {}, query = {}, user = {}, pg = pgClients.client }, reply) {
    if (!params.id) {
        return reply.status(400).send({ error: "not enough params: id", code: 400 });
    }

    const service = await pg.query(`SELECT source_path as table, style, legend as dblegend FROM gis.services where service_id=$1`, [params.id]).then(el => el.rows?.[0]);

    if (!service) {
        return reply.status(404).send({ error: "Service not found", code: 404 });
    }

    const { style, dblegend, table } = service;

    if (!table) {
        return reply.status(400).send({ error: "service table not specified", code: 400 });
    }

    if (dblegend && !query.nocache) {
        return reply.status(400).send({ error: "legend already exists", code: 400 });
    }

    if (!style) {
        return reply.status(400).send({ error: "empty service style", code: 400 });
    }

    const { colorAttr, iconAttr } = yml2json(style);

    if (!colorAttr && !iconAttr) {
        return reply.status(400).send({ error: "colorAttr / iconAttr not specified", code: 400 });
    }

    const { columns = [] } = await getMeta({ pg, table });

    const attr = columns.find(col => col.name === (colorAttr || iconAttr));

    if (!attr?.name) {
        return reply.status(404).send({ error: "attribute column not found", code: 404 });
    }

    const values = await pg.query(`select array_agg(distinct "${attr.name}") from ${table}`).then(el => el.rows?.[0]?.array_agg || []);
    const arr = await getSelectVal({ pg, name: `${table}.${attr.name}`, table, values, ar: true });

    const colors = {
        1: "#FFCF1F1F",
        2: "#FF1FCF2D",
        3: "#FF1F77CF"
    };

    const colorKeys = Object.keys(colors).map(Number);

    const legend = arr
        ? arr.map((el, idx) => ({
            name: el.id,
            label: el.text,
            icon: iconAttr ? el.icon : undefined,
            color: colorAttr ? (el.color || colors[colorKeys[idx % colorKeys.length]]) : undefined,
        }))
        : values.map((el, idx) => ({
            name: el,
            label: el,
            icon: undefined,
            color: colorAttr ? (colors[colorKeys[idx % colorKeys.length]]) : undefined,
        }));

    const res = await dataUpdate({
        pg,
        table: 'gis.services',
        id: params.id,
        data: {
            legend
        },
        uid: user.uid,
    });

    return reply.status(200).send(res);
}