public.ts 1.62 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
import {RECEIVE_CROP_DETAILS, RECEIVE_CROPS, UPDATE_CROPS_LIST} from 'crop/constants';
import Crop from 'model/genesys/Crop';
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
6
import ApiCall from 'model/ApiCall';
Maxym Borodenko's avatar
Maxym Borodenko committed
7 8

const INITIAL_STATE: {
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
9 10
    list: ApiCall<Crop[]>,
    details: ApiCall<Crop>,
Maxym Borodenko's avatar
Maxym Borodenko committed
11
} = {
12
    list: null,
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
13
    details: null,
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
14 15 16 17 18 19
};

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

    switch (action.type) {
        case RECEIVE_CROPS: {
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
20 21 22 23
            const {apiCall} = action.payload;

            apiCall.data = apiCall.data ? apiCall.data.sort((a, b) => a.name.localeCompare(b.name)) : null;

Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
24
            return update(state, {
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
25
                list: {$set: apiCall},
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
26 27
            });
        }
Maxym Borodenko's avatar
Maxym Borodenko committed
28
        case UPDATE_CROPS_LIST: {
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
29
            const updateIndex = state.list && action.payload ? state.list.data.findIndex((crop) => crop.shortName === action.payload.shortName) : -1;
30 31 32 33

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

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

        default:
            return state;
    }

}