sectorcourses.reducer.ts 2.08 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
import { List } from "immutable";
import { recordify } from "typed-immutable-record";

import { SECTORCOURSES_INIT, SECTORCOURSES_RECEIVED, SECTORCOURSES_SELECTED_SAVE } from "../../constants";
import { SECTOR_COURSES_INITIAL_STATE } from "./sectorcourses.initial-state";
import { ISector, ISectorCourse, ISectorCourseRecord, ISectorRecord, ISectorRecords } from "./sectorcourses.types";

export function sectorCoursesReducer(state: ISectorRecords = SECTOR_COURSES_INITIAL_STATE, action): ISectorRecords {
    switch (action.type) {
        case SECTORCOURSES_RECEIVED:
        let newSectors = Array<ISectorRecord>();
        let newCourses = Array<ISectorCourseRecord>();
        let i = 0, j = 0;
        let ii = 0;

        action.payload.sectors.forEach(sector => {
            sector.courses.forEach(course => {
                newCourses.push(recordify<ISectorCourse, ISectorCourseRecord>({ course_id: course.course_id, course_name: course.course_name, globalIndex: course.globalIndex, selected: course.selected }));
                ii++;
            });
            newSectors.push(recordify<ISector, ISectorRecord>({ sector_id: sector.sector_id, sector_name: sector.sector_name, sector_selected: sector.sector_selected, courses: List(newCourses) }));
            newCourses = Array<ISectorCourseRecord>();
            i++;
        });
        return List(newSectors);

        case SECTORCOURSES_SELECTED_SAVE:
            return state.withMutations(function(list) {
                list.setIn([action.payload.oldSIndex, "sector_selected"], false);
                list.setIn([action.payload.sIndex, "sector_selected"], true);
                list.setIn([action.payload.oldSIndex, "courses"], list.get(action.payload.oldSIndex).get("courses").setIn([action.payload.oldCIndex, "selected"], false));
                list.setIn([action.payload.sIndex, "courses"], list.get(action.payload.sIndex).get("courses").setIn([action.payload.cIndex, "selected"], action.payload.checked));
            });

        case SECTORCOURSES_INIT:
            return SECTOR_COURSES_INITIAL_STATE;
        default: return state;
    }
};