import {atom, selector, selectorFamily} from 'recoil';
import {getManufacturers} from '../api/manufacturersAPI';

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

export const manufacturersState = selector({
    key: 'manufacturersState',
    get: ({get}) => {
        return get(manufacturersCache) || getManufacturers();
    },
    set: ({set}, newValue) => {
        set(manufacturersCache, newValue);
    }
})

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