import Row from '../Row';
import Column from '../Column';
import Context from '../Context';
import ConditionOrFilter from '../conditionsOrFilters/ConditionOrFilter';
import createCard from '../conditionsOrFilters/CardCreator';
import Offer from '../conditionsOrFilters/Offer';
import { CouponsPlus } from '../globals';
import {cloneDeep} from 'lodash';
export default class RowsMapper
{
    constructor(rows, preconditionsColumn) 
    {
        this.rows = rows || [];
        this.preconditionsColumn = preconditionsColumn || [];
    }

    getRows() 
    {
        return [
            ...this.rows,
            typeof this.preconditionsColumn !== 'undefined'? Row.map({
                "type":window.CouponsPlus.components.rows.types.preconditions,
                "temporaryID": 'preconditions-row',
                "columns": [
                    this.preconditionsColumn
                ]
            }) : null
        ].filter(col => !!col)
    }

    map() 
    {
        for (let [rowIndex, row] of this.getRows().entries()) {
            row = Row.map(row);
            this.rows[rowIndex] = row;

            for (let [columnIndex, column] of row.columns.entries()) {
                column = Column.map(column);
                row.columns[columnIndex] = column;

                for (let [offerIndex, offer] of column.defaultOffers.entries()) {
                    offer = this.mapOffer(offer)
                    column.defaultOffers[offerIndex] = offer;
                }  

                for (let [contextIndex, context] of column.contexts.entries()) {
                    context = Context.map(context);
                    column.contexts[contextIndex] = context;

                    //conditions or filters
                    for (let [conditionOrFilterIndex, conditionOrFilter] of context.conditionsOrFilters.entries()) {
                        conditionOrFilter = ConditionOrFilter.map(conditionOrFilter);
                        context.conditionsOrFilters[conditionOrFilterIndex] = conditionOrFilter;
                    }  

                    //offers
                    for (let [offerIndex, offer] of context.offers.entries()) {
                        offer = this.mapOffer(offer)
                        context.offers[offerIndex] = offer;
                    }  
                }   
            }
        }

        return this.rows;
    }

    mapOffer(offer) 
    {
        const offerCard = createCard('offers', offer)
        
        offer = offerCard.data;

        return offer
    }
}