import {atom, selector, selectorFamily} from 'recoil';
import {getRobots} from '../api/robotsAPI';

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

export const robotsState = selector({
    key: 'robots',
    get: ({get}) => {
        return get(robotCache)|| getRobots();
    },
    set: ({set}, newValue) => {
        set(robotCache, newValue);
    }
})

export const robotById = selectorFamily({
    key: 'robotById',
    get: id => ({get}) => {
        id = Number(id);
        return get(robotsState).find(r => r.id === id);
    },
    set: id => ({get, set}, newValue) => {
        id = Number(id);
        let robots = [...get(robotsState)];
        if (id) {
            robots = robots.map(r => r.id === id ? newValue : r);
        } else {
            robots.push(newValue);
        }
        set(robotsState, robots);
    }
})
