import {atom, selector, selectorFamily} from 'recoil';
import {getCategories} from '../api/categoriesAPI';

const categoriesCache = atom({
    key: 'categoriesCache',
    default: undefined
})

export const categoriesState = selector({
    key: 'categoriesState',
    get: ({get}) => {
        return get(categoriesCache) || getCategories();
    },
    set: ({set}, newValue) => {
        set(categoriesCache, newValue);
    }
})

export const categoryById = selectorFamily({
    key: 'categoryById',
    get: id => ({get}) => {
        id = Number(id);
        return get(categoriesState).find(c => c.id === id);
    },
    set: id => ({get, set}, newValue) => {
        id = Number(id);
        let categories = [...get(categoriesState)];
        if (id) {
            categories = categories.map(c => c.id === id ? newValue : c);
        } else {
            categories.push(newValue);
        }
        set(categoriesState, categories);
    }
})
