UPDATE parkings.parking_sources SET legacy_api_allowed = false WHERE source = 'tsk_v2';
UPDATE parkings.parking_sources SET legacy_api_allowed = true WHERE source = 'tsk';



CREATE MATERIALIZED VIEW IF NOT EXISTS v_tsk_average_occupancy AS
WITH average_occupancy_agg AS (
	SELECT
		"source_id",
		extract(dow FROM "date_modified" AT TIME ZONE 'Europe/Prague')::text AS "day_of_week",
		extract(hour FROM "date_modified" AT TIME ZONE 'Europe/Prague') AS "hour",
		round(avg("occupied_spot_number"))::int AS "average_occupancy"
	FROM parkings_measurements_part
	WHERE "source" IN ('tsk', 'TSK') AND "date_modified" > NOW() - interval '1 month'
	GROUP BY 1, 2, 3
	ORDER BY 1, 2, 3
),
average_occupancy_hour_json_agg AS (
	SELECT
		"source_id",
		"day_of_week",
		json_object_agg(lpad("hour"::text, 2, '0'), "average_occupancy" ORDER BY 1) AS "hour_agg"
	FROM average_occupancy_agg
	GROUP BY 1, 2
)
SELECT
	"source_id",
	json_object_agg(lpad("day_of_week", 2, '0'), "hour_agg") AS "average_occupancy"
FROM average_occupancy_hour_json_agg
GROUP BY 1;

CREATE UNIQUE INDEX v_tsk_average_occupancy_idx ON v_tsk_average_occupancy USING btree (source_id);

CREATE TABLE parkings_business_errors (
	identifier uuid NOT NULL,
	provider varchar(10) NOT NULL,
    record_date date NOT NULL,
    "type" varchar(50) NOT NULL,
	detail json NOT NULL,	
	CONSTRAINT parkings_business_errors_pk PRIMARY KEY (identifier,provider,record_date)
);

INSERT INTO parking_sources("source", open_data, api_v3_allowed, contact, legacy_api_allowed, datasource_parking, datasource_locations, datasource_payments, payment, reservation, datasource_entrances, datasource_prohibitions, "name", datasource_tariffs) VALUES
('tsk', false, false, '{"email": "parking@tsk-praha.cz", "phone": "+420 257 015 257", "web_url": "https://parking.praha.eu/", "term_of_use_url": "https://parking.praha.eu/cs/moznosti-parkovani-v-praze/parkovani-v-zonach/"}'::jsonb, false, NULL, NULL, NULL, '{"ios_url": null, "web_url": "", "android_url": null, "discovery_url": null}'::jsonb, NULL, NULL, NULL, 'Technická správa komunikací hl. m. Prahy', NULL);
