DROP VIEW IF EXISTS analytic.v_ropid_departure_boards;


alter table ropid_departures_presets rename to ropid_departures_presets_old;
CREATE TABLE ropid_departures_presets (
    id integer DEFAULT nextval('ropid_departures_presets_id_seq'::regclass) NOT NULL,
    route_name character varying(100) NOT NULL,
    api_version smallint NOT NULL,
    route character varying(100) NOT NULL,
    url_query_params character varying(400),
    note character varying(1000) NOT NULL,
    is_testing boolean not null default false,

    create_batch_id bigint,
    created_at timestamp with time zone,
    created_by character varying(150),
    update_batch_id bigint,
    updated_at timestamp with time zone,
    updated_by character varying(150),

    CONSTRAINT ropid_departures_presets_new_pkey PRIMARY KEY (id)
);

create unique index ropid_departures_presets_new_unique_idx on ropid_departures_presets (route_name);
insert into ropid_departures_presets (route_name, api_version, route, url_query_params, note, is_testing, create_batch_id, created_at, created_by, update_batch_id, updated_at, updated_by)
    select route_name, api_version, route, url_query_params, note, is_testing, create_batch_id, created_at, created_by, update_batch_id, updated_at, updated_by
    from ropid_departures_presets_old;

drop table ropid_departures_presets_old;


CREATE OR REPLACE VIEW analytic.v_ropid_departure_boards
AS SELECT final.lon,
          final.lat,
          final.route_name,
          final.note,
          final.stop_correct,
          count(1) OVER (PARTITION BY (split_part(final.stop_correct, '/'::text, 1))) AS n_ceduli,
          final.alt_idos_name
   FROM ( SELECT stops.lon,
                 stops.lat,
                 tab.route_name,
                 tab.note,
                 tab.stop_correct,
                 stops.alt_idos_name,
                 row_number() OVER (PARTITION BY tab.note) AS n_duplicit
          FROM ( SELECT rdp.route_name,
                        rdp.note,
                        CASE
                            WHEN rdp.url_query_params::text ~~ '%aswIds%'::text THEN replace("substring"(rdp.url_query_params::text, 'aswIds[^=]*?=(.+?(?=&|$))'::text), '_'::text, '/'::text)
                            WHEN rdp.url_query_params::text ~~ '%cisIds%'::text THEN "substring"(rdp.url_query_params::text, 'cisIds[^=]*?=(.+?(?=&|$))'::text)
                            ELSE NULL::text
                            END AS stop_correct
                 FROM ropid_departures_presets rdp) tab
                   LEFT JOIN ropidgtfs_cis_stops stops ON
                  CASE
                      WHEN tab.stop_correct ~~ '%/%'::text THEN tab.stop_correct = stops.id::text
                      ELSE tab.stop_correct = split_part(stops.id::text, '/'::text, 1)
                      END OR tab.stop_correct = stops.cis::text) final
   WHERE final.n_duplicit = 1
   ORDER BY final.stop_correct;
