from django.core.management.base import BaseCommand
from service.utils import run_sql_command, log_to_telegram

CMD_PIVOT_DIST = """CREATE OR REPLACE VIEW compact_placementpoint AS
SELECT id, status, category, age_day, fact, area_id, district_id, prediction_first, prediction_current, doors, flat_cnt, rival_post_cnt, rival_pvz_cnt, target_post_cnt, flats_cnt, tc_cnt, culture_cnt, mfc_cnt, public_stop_cnt, supermarket_cnt, target_dist, metro_dist, geometry, delta_first, delta_current FROM service_placementpoint;
CREATE OR REPLACE procedure pivot_dist()
AS $BODY$
DECLARE columnNames TEXT;
BEGIN
DROP MATERIALIZED VIEW IF EXISTS points_with_dist;
SELECT 'placement_point_id bigint, ' || string_agg(c, ', ') FROM (SELECT distinct pvz_postamates_group_id, 'd' || pvz_postamates_group_id || ' double precision' as c from service_placementpointpvzdistance order by 1) as asd
INTO columnNames;
IF columnNames IS NOT NULL
THEN
EXECUTE format('CREATE MATERIALIZED VIEW points_with_dist AS SELECT *
FROM CROSSTAB(
    $$
    SELECT placement_point_id, pvz_postamates_group_id, dist
    FROM service_placementpointpvzdistance
    ORDER BY 1, 2
    $$
) AS ct(%s)
LEFT JOIN compact_placementpoint ON placement_point_id=id'
	,columnNames);
ELSE
CREATE MATERIALIZED VIEW points_with_dist AS SELECT placement_point_id, compact_placementpoint.id, status, category, age_day, fact, area_id, district_id, prediction_first, prediction_current, doors, flat_cnt, rival_post_cnt, rival_pvz_cnt, target_post_cnt, flats_cnt, tc_cnt, culture_cnt, mfc_cnt, public_stop_cnt, supermarket_cnt, target_dist, metro_dist, geometry, delta_first, delta_current FROM service_placementpointpvzdistance LEFT JOIN compact_placementpoint ON placement_point_id=compact_placementpoint.id;
END IF;
END;
$BODY$
LANGUAGE plpgsql;
"""

CMD_PIVOT_DIST_PRE = """CREATE OR REPLACE VIEW compact_preplacementpoint AS
SELECT id, status, category, age_day, fact, area_id, district_id, prediction_first, prediction_current, doors, flat_cnt, rival_post_cnt, rival_pvz_cnt, target_post_cnt, flats_cnt, tc_cnt, culture_cnt, mfc_cnt, public_stop_cnt, supermarket_cnt, target_dist, metro_dist, geometry, delta_first, delta_current FROM service_preplacementpoint;
CREATE OR REPLACE procedure prepivot_dist()
AS $BODY$
DECLARE columnNames TEXT;
BEGIN
DROP MATERIALIZED VIEW IF EXISTS prepoints_with_dist;
SELECT 'preplacement_point_id bigint, ' || string_agg(c, ', ') FROM (SELECT distinct pvz_postamates_group_id, 'd' || pvz_postamates_group_id || ' double precision' as c from service_preplacementpointpvzdistance order by 1) as asd
INTO columnNames;
IF columnNames IS NOT NULL
THEN
EXECUTE format('CREATE MATERIALIZED VIEW prepoints_with_dist AS SELECT *
FROM CROSSTAB(
    $$
    SELECT placement_point_id, pvz_postamates_group_id, dist
    FROM service_preplacementpointpvzdistance
    ORDER BY 1, 2
    $$
) AS ct(%s)
LEFT JOIN compact_preplacementpoint ON preplacement_point_id=id'
	,columnNames);
ELSE
CREATE MATERIALIZED VIEW prepoints_with_dist AS SELECT placement_point_id, compact_preplacementpoint.id, status, category, age_day, fact, area_id, district_id, prediction_first, prediction_current, doors, flat_cnt, rival_post_cnt, rival_pvz_cnt, target_post_cnt, flats_cnt, tc_cnt, culture_cnt, mfc_cnt, public_stop_cnt, supermarket_cnt, target_dist, metro_dist, geometry, delta_first, delta_current FROM service_preplacementpointpvzdistance LEFT JOIN compact_preplacementpoint ON placement_point_id=compact_preplacementpoint.id;
END IF;
END;
$BODY$
LANGUAGE plpgsql;
"""
class Command(BaseCommand):
    help = 'Create procedures'

    def handle(self, *args, **kwargs):
        try:
            log_to_telegram('Creating procedures')
            run_sql_command(CMD_PIVOT_DIST)
            log_to_telegram('pivot_dist created')
            run_sql_command(CMD_PIVOT_DIST_PRE)
            log_to_telegram('prepivot_dist created')
        except Exception as e:
            log_to_telegram('Error creating views: ' + str(e))