import { copyOfTheState } from './copyOfTheState';
import Row from '../Row';
import { cloneDeep } from 'lodash';
import { getPreconditionsRow } from '../Preconditions';
import RowsMapper from '../data/RowsMapper';
export default class RowsReducers
{
    static getReducers()
    {
        return {
            'rows/add': RowsReducers.onNewRow,
            'rows/remove': RowsReducers.onRemoveRow,
            'rows/set': RowsReducers.onSetRows
        }
    }

    static onNewRow(state, action) 
    {
        return copyOfTheState(state, state => {
            const newRow = cloneDeep(Row.structure());

            if (action.payload.afterOptionalRowTemporaryId) {
                state.rows.splice(
                    state.rows.findIndex(row => row.temporaryID === action.payload.afterOptionalRowTemporaryId) + 1,
                    0,
                    newRow
                );
            } else {
                state.rows.push(newRow);
            }
        })
    }

    static onRemoveRow(state, action) 
    {
        return copyOfTheState(state, state => {
            state.rows = state.rows.filter(row => row.temporaryID !== action.payload.rowTemporaryId)
        })
    }

    static onSetRows(state, {payload: {rows}}) 
    {
        return copyOfTheState(state, state => {
            const oldRows = cloneDeep(state.rows)

            if (Array.isArray(rows)) {
                state.rows = rows;
            }

            //if we dont have a preconditions row, add it from the currentRows
            //IT IS IMPORTANT TO ADD IT FROM THE CURRENT ROWS SO AS TO PRESERVE THE CURRENT PRECONDIITONS IF ANY
            if (!getPreconditionsRow(state.rows)) {
                state.rows = [
                    ...state.rows,
                    getPreconditionsRow(oldRows)
                ]
            }

            /**
             * VERY IMPORTANT TO MAP THE ROWS SO THAT OLDER DATA IS MAPPED TO NEW OPTIONS
             * INTRODUCED IN NEWER VERSIONS OF COUPONS+ 
             */
            const rowsMapper = new RowsMapper(state.rows)

            state.rows = rowsMapper.map()
        })
    }
}