import { createSlice, PayloadAction } from '@reduxjs/toolkit' import { PaginationMeta } from '../common' export interface InterrailTime { hours: number minutes: number offset: number } export interface InterrailDate { day: number month: number year: number } export interface InterrailTravelInfo { arrivalTime: InterrailTime date: InterrailDate departureTime: InterrailTime haconVersion: number dataSource: number } export interface InterrailStopExtraInfo { departureTime: InterrailTime index: number } export interface InterrailStopCoordinates { latitude: number longitude: number } export interface InterrailStopStation { coordinates: InterrailStopCoordinates country: string name: string stationId: number } export interface InterrailLegInfo { attributeCodes: string[] attributes: object duration: InterrailTime directionStation: string endTime: InterrailTime isSeparateTicket: boolean operationDays: string operator: object dataSource: number startTime: InterrailTime stopExtraInfo: InterrailStopExtraInfo[] trainName: string trainStopStations: InterrailStopStation[] trainType: number } export interface TrainTrip { id: string distance: number, from: string, to: string, departureTime: number, arrivalTime: number, infoJson?: string, info?: InterrailLegInfo, } export interface TrainsState { trains: TrainTrip[] } const initialState: TrainsState = { trains: [] } export interface TrainsPayload { data: TrainTrip[] meta: PaginationMeta } export const trainSlice = createSlice({ name: 'train', initialState: initialState, reducers: { downloadTrains(state, action: PayloadAction) { if (state.trains) state.trains = state.trains.filter(train => action.payload.data.filter(dlTrain => dlTrain.id === train.id) === null) for (const dlTrain of action.payload.data) { const info = dlTrain.infoJson ? JSON.parse(dlTrain.infoJson) : undefined state.trains.push({ id: dlTrain.id, distance: dlTrain.distance, from: dlTrain.from, to: dlTrain.to, departureTime: dlTrain.departureTime, arrivalTime: dlTrain.arrivalTime, info: info, }) } state.trains.sort((t1, t2) => t1.departureTime > t2.departureTime ? -1 : t1.departureTime == t2.arrivalTime ? 0 : 1) } }, }) export const {downloadTrains } = trainSlice.actions export default trainSlice.reducer