import {UPDATE_ITEM_CHECK_STATES} from "constants/items";
import _ from "lodash";

import {schema, getModelByType} from "models/models";

export function updateCheckStateForModels(state, action) {
    const {payload} = action;
    const session = schema.from(state);

    const {newCheckState, leaves, otherItems, itemID, itemType} = payload;

    // Create a list of all changed items, clicked item first
    const allChangedItems = [{itemID, itemType}].concat(leaves, otherItems);

    // Look up all explicitly changed items, hydrate models, and update their checkstates
    const allChangedModels = allChangedItems.map(item => {
        const itemModel = getModelByType(session, item.itemID, item.itemType);
        itemModel.checked = newCheckState;
        return itemModel;
    });

    const startingModel = _.first(allChangedModels);

    let ancestor = startingModel.parent;

    // Recurse upwards and recalculate dependent checkstates from the new values
    while(ancestor) {
        ancestor.updateCheckState();
        ancestor = ancestor.parent;
    }

    return session.reduce();
}

export default function entitiesReducer(state = initialState, action) {
    switch(action.type) {
        case UPDATE_ITEM_CHECK_STATES:
            return updateCheckStateForModels(state, action);
        default:
            return state;
    }
}