public.ts 1.47 KB
Newer Older
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
1 2 3
import update from 'immutability-helper';

import { IReducerAction } from 'model/common.model';
Maxym Borodenko's avatar
Maxym Borodenko committed
4 5 6 7 8 9 10 11
import {RECEIVE_CROP_DETAILS, RECEIVE_CROPS, UPDATE_CROPS_LIST} from 'crop/constants';
import Crop from 'model/genesys/Crop';

const INITIAL_STATE: {
    list: Crop[],
    lastFetched: number,
    details: Crop,
} = {
12
    list: null,
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
13
    lastFetched: 0,
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
14
    details: null,
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
15 16 17 18 19 20 21
};

export default function crop(state = INITIAL_STATE, action: IReducerAction = {type: ''}) {

    switch (action.type) {
        case RECEIVE_CROPS: {
            return update(state, {
22
                list: {$set: action.payload},
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
23 24 25
                lastFetched: {$set: Date.now()},
            });
        }
Maxym Borodenko's avatar
Maxym Borodenko committed
26
        case UPDATE_CROPS_LIST: {
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
27
            const updateIndex = state.list && action.payload ? state.list.findIndex((crop) => crop.shortName === action.payload.shortName) : -1;
28 29 30 31

            return updateIndex === -1 ?
                update(state, {
                    details: {$set: null},
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
32
                    list: {$push: action.payload ? [action.payload] : []},
33 34 35 36 37 38 39 40 41
                })
                :
                update(state, {
                    details: {$set: null},
                    list: {
                        [updateIndex]: {$set: action.payload},
                    },
                });

Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
42 43 44 45 46 47
        }
        case RECEIVE_CROP_DETAILS: {
            return update(state, {
                details: {$set: action.payload},
            });
        }
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
48 49 50 51 52 53

        default:
            return state;
    }

}