regionschools.reducer.ts 2.28 KB
Newer Older
1
import { IRegions, IRegion, IRegionSchool } from './regionschools.types';
2
import { REGION_SCHOOLS_INITIAL_STATE } from './regionschools.initial-state';
3 4 5 6
import { Seq } from 'immutable';

import {
  REGIONSCHOOLS_RECEIVED,
7
  REGIONSCHOOLS_SELECTED_SAVE,
8 9
  REGIONSCHOOLS_ORDER_SAVE,
  REGIONSCHOOLS_INIT
10 11
} from '../../constants';

12
export function regionSchoolsReducer(state: IRegions = REGION_SCHOOLS_INITIAL_STATE, action): IRegions {
13 14 15 16 17 18 19
  switch (action.type) {
    case REGIONSCHOOLS_RECEIVED:
        let newRegions = Array<IRegion>();
        let i=0;
        action.payload.regions.forEach(region => {
            newRegions.push(<IRegion>{region_id: region.region_id, region_name: region.region_name, epals: Array<IRegionSchool>() });
            region.epals.forEach(epal => {
20
                newRegions[i].epals.push(<IRegionSchool>{epal_id: epal.epal_id, epal_name: epal.epal_name, globalIndex: epal.globalIndex, selected: epal.selected, order_id: epal.order_id });
21 22 23 24 25
            })
            i++;
        });
        return Seq(newRegions).map(n => n).toList();
    case REGIONSCHOOLS_SELECTED_SAVE:
26
        let ind=0;
27
        state.forEach(region => {
28 29 30 31 32 33
            if (ind === action.payload.rIndex) {
                region.epals[action.payload.sIndex].selected = action.payload.checked;
                return state.withMutations(function (list) {
                    list.set(ind++, region);
                });
            }
34 35
            ind++;
        });
36
        return state;
37 38 39 40 41 42 43 44 45 46 47 48 49 50

        case REGIONSCHOOLS_ORDER_SAVE:
            let regionsWithOrders = Array<IRegion>();
            let idx=0, k = 0;
            state.forEach(region => {
                regionsWithOrders.push(<IRegion>{region_id: region.region_id, region_name: region.region_name, epals: Array<IRegionSchool>()});
                region.epals.forEach(epal => {
                    regionsWithOrders[idx].epals.push(<IRegionSchool>{epal_id: epal.epal_id, epal_name: epal.epal_name, globalIndex: epal.globalIndex, selected: epal.selected, order_id: action.payload.regionSchoolsOrder[k]});
                    k++;
                })
                idx++;
            });
            return Seq(regionsWithOrders).map(n => n).toList();

51 52
        case REGIONSCHOOLS_INIT:
            return REGION_SCHOOLS_INITIAL_STATE;
53 54 55
    default: return state;
  }
};