import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { MemberType } from './MemberType';
import memoize from 'proxy-memoize';
import type { StoreState } from '../Store/store';

export const prayerCircleSlice = createSlice({
    name: 'prayerCircle',
    initialState: {
        members: {} as Record<string, MemberType>,
        week: 0,
        useWeekdays: false,
        usePartners: true,
    },
    reducers: {
        saveMember: (state, action: PayloadAction<MemberType>) => {
            const member = action.payload;
            state.members[member.id] = member;
        },
        removeMember: (state, { payload: memberId }: PayloadAction<string>) => {
            delete state.members[memberId];
        },
        setWeek: (state, { payload: week }: PayloadAction<number>) => {
            state.week = week;
        },
        setUseWeekdays: (state, { payload: useWeekdays }: PayloadAction<boolean>) => {
            state.useWeekdays = useWeekdays;
        },
        setUsePartners: (state, { payload: usePartners }: PayloadAction<boolean>) => {
            state.usePartners = usePartners;
        },
    },
});

export const { saveMember, removeMember, setWeek, setUseWeekdays, setUsePartners } = prayerCircleSlice.actions;
export const { reducer: prayerCircle } = prayerCircleSlice;

export const selectMembers = memoize((state: StoreState) => Object.values(state.prayerCircle.members));
export const selectMemberIds = memoize((state: StoreState) => Object.keys(state.prayerCircle.members));
