DROP FUNCTION departure_part (text, text, boolean);

ALTER TABLE ropidgtfs_services_first14days rename to ropidgtfs_precomputed_services_calendar;
ALTER TABLE ropidgtfs_services_first14days_actual rename to ropidgtfs_precomputed_services_calendar_actual;

ALTER TABLE ropidgtfs_trips_minmaxsequences rename to ropidgtfs_precomputed_minmax_stop_sequences;
ALTER TABLE ropidgtfs_trips_minmaxsequences_actual rename to ropidgtfs_precomputed_minmax_stop_sequences_actual;

ALTER TABLE ropidgtfs_scheduled_trips rename to ropidgtfs_precomputed_trip_schedule;
ALTER TABLE ropidgtfs_scheduled_trips_actual rename to ropidgtfs_precomputed_trip_schedule_actual;

CREATE TABLE ropidgtfs_precomputed_departures
    AS SELECT * FROM ropidgtfs_departures WHERE "date" = current_date;
ALTER TABLE ropidgtfs_precomputed_departures drop column part_index;
CREATE INDEX ropidgtfs_precomputed_departures_stop_id_idx ON ropidgtfs_precomputed_departures USING btree (stop_id);
CREATE UNIQUE INDEX ropidgtfs_precomputed_departures_unique_idx ON ropidgtfs_precomputed_departures USING btree (date, trip_id, stop_sequence);

DROP TABLE ropidgtfs_departures;
DROP TABLE IF EXISTS ropidgtfs_departures_tmp;

CREATE OR REPLACE FUNCTION gtfs_timestamp(gtfs_time varchar, target_date date)
RETURNS timestamptz AS
$$
BEGIN
    RETURN CASE
        WHEN (date_part('hour'::text, (gtfs_time)::interval) > (23)::double precision) THEN make_timestamptz((date_part('year'::text, (target_date + '1 day'::interval)))::integer, (date_part('month'::text, (target_date + '1 day'::interval)))::integer, (date_part('day'::text, (target_date + '1 day'::interval)))::integer, ((date_part('hour'::text, (gtfs_time)::interval))::integer - 24), (date_part('minute'::text, (gtfs_time)::interval))::integer, date_part('second'::text, (gtfs_time)::interval), 'Europe/Prague'::text)
        ELSE make_timestamptz((date_part('year'::text, target_date))::integer, (date_part('month'::text, target_date))::integer, (date_part('day'::text, target_date))::integer, (date_part('hour'::text, (gtfs_time)::interval))::integer, (date_part('minute'::text, (gtfs_time)::interval))::integer, date_part('second'::text, (gtfs_time)::interval), 'Europe/Prague'::text)
    END;
END;
$$
LANGUAGE plpgsql;

COMMENT ON FUNCTION gtfs_timestamp(gtfs_time varchar, target_date date) IS '
Converts a time string from GTFS feed to a timestamp.
If the GTFS time string represents a time later than 23:59, the timestamp returned will be for the day following the target date, with the hour adjusted accordingly.
Otherwise, the timestamp returned will be for the target date.
';
