import {
    AddIterableSectionAction,
    IterableAction,
    RemoveIterableSectionAction,
    SimpleAction,
    WithSumAction
} from "./interfaces";

export function reducer(
    state: Record<string, any>,
    action: SimpleAction | WithSumAction | IterableAction | AddIterableSectionAction | RemoveIterableSectionAction
): Record<string, any> {
    const newState: Record<string, any> = { ...state };

    switch (action.type) {
        case "simple": {
            const { value, key } = action;
            newState[key] = value;
            break;
        }

        case "with_sum": {
            const { value, key, key_prefix = '' } = action;
            const sum_key = key_prefix + 'sum';
            newState[key] = value;
            newState[sum_key] = (state[sum_key] * 1 || 0) - (state[key] * 1 || 0) + (Number(value) || 0);
            break;
        }

        case "iterable": {
            const { value, key, iterable_count } = action;
            newState[key][iterable_count] = value;
            break;
        }

        case "add_iterable_section": {
            const { section, sec_i } = action;
            section.form_fields.forEach(field => {
                switch (field.type) {
                    case 'text':
                        newState[field.name].push('');
                        break;
                    case 'select':
                        newState[field.name].push(0);
                        break;
                    case 'date':
                        newState[field.name].push('');
                        break;
                    default:
                        throw Error(
                            'THIS SECTION HAS FIELDS TYPE THAT CANNOT BE REPLICATED FOR NOW: ' +
                            field.type.toUpperCase() +
                            ' PLEASE ABORT'
                        );
                }
            });
            newState.meta[section.name + '_count'] = state.meta[section.name + '_count'] + 1;
            break;
        }

        case "remove_iterable_section": {
            const { section, sec_i, iterable_count } = action;
            section.form_fields.forEach(field => {
                newState[field.name].splice(iterable_count, 1);
            });
            newState.meta[section.name + '_count'] = state.meta[section.name + '_count'] - 1;
            break;
        }
    }

    return newState;
}
