import * as R from "ramda"; import {ActionType, createReducer} from "deox"; import {Subject} from "rxjs"; import {IrisChannel, IrisMessage, IrisSimChannel} from ".."; import {actions} from "./iris.action"; import Cookies from 'js-cookie' export type IrisUserType = { jwt: string; }; export interface IrisState { user: IrisUserType | null; channel: IrisChannel | null; simChannel: IrisSimChannel | null; subject: Subject | null; authenticationError?: Error; } export const initialState: IrisState = { user: Cookies.getJSON('iris.user'), channel: Cookies.getJSON('iris.channel'), simChannel: Cookies.getJSON('iris.simChannel'), subject: null, }; export type LoginStateTransformer = (state: IrisState) => IrisState; const setUser = (user: IrisUserType): LoginStateTransformer => { Cookies.set('iris.user', user, { expires: 7 }); return R.assoc("user", user); }; const removeUser = (): LoginStateTransformer => { Cookies.remove('iris.user'); return R.assoc("user", null); }; const setIrisChannel = (channel: IrisChannel) => { Cookies.set('iris.channel', channel, { expires: 7 }); return R.assoc("channel", channel); }; const removeChannel = (): LoginStateTransformer => { Cookies.remove('iris.channel'); return R.assoc("channel", null); }; const setAuthenticationError = (error: Error | undefined) => R.assoc("authenticationError", error); const setIrisSubject = ($subject: Subject) => R.assoc("subject", $subject); const removeIrisSubject = () => R.assoc("subject", null); const setSimChannel = (channel: IrisSimChannel) => { Cookies.set('iris.simchannel', channel, { expires: 7 }); return R.assoc("simChannel", channel); }; const removeSimChannel = (): LoginStateTransformer => { Cookies.remove('iris.simChannel'); return R.assoc("simChannel", null); }; export const irisReducer = createReducer(initialState, handleAction => [ handleAction( actions.createdIrisChannel, ( state: IrisState, action: ActionType ) => R.pipe( setIrisChannel(action.payload.channel) )(state) ), handleAction( actions.linkedPhoneNumber, ( state: IrisState, action: ActionType ) => R.pipe(setSimChannel(action.payload.simChannel))(state) ), handleAction( actions.connectedIrisChannel, ( state: IrisState, action: ActionType ) => R.pipe(setIrisSubject(action.payload.$subject))(state) ), handleAction( actions.receivedAuthIrisResponse, ( state: IrisState, action: ActionType ) => R.pipe( setUser({jwt: action.payload.jwt}), setAuthenticationError(undefined) )(state) ), handleAction( actions.logout, (state: IrisState, action: ActionType) => R.pipe( removeUser(), removeChannel(), removeSimChannel(), removeIrisSubject(), setAuthenticationError(undefined) )(state) ) ]);