export default class RowsComponentsFinder
{
    rowsCopy = [];

    constructor(rowsCopy)
    {
        this.rowsCopy = rowsCopy;
    }

    find(temporaryID)
    {
        let foundFromOffer

        for (let row of this.rowsCopy) { 
            if (row.temporaryID === temporaryID) {
                return row;
            }

            for (let column of row.columns) {
                if (column.temporaryID === temporaryID) {
                    return column;
                }

                for (let defaultOffer of column.defaultOffers) {
                    if (defaultOffer.temporaryID === temporaryID) {
                        return defaultOffer;
                    }

                    if (foundFromOffer = this.findFromOffer(defaultOffer, temporaryID)) {
                        return foundFromOffer
                    }

                }

                for (let context of column.contexts) {
                    if (context.temporaryID === temporaryID) {
                        return context;
                    }

                    for (let conditionOrFilter of context.conditionsOrFilters) {
                        if (conditionOrFilter.temporaryID === temporaryID) {
                            return conditionOrFilter;
                        }
                    }

                    for (let offer of context.offers) {
                        if (offer.temporaryID === temporaryID) {
                            return offer;
                        }

                        if (foundFromOffer = this.findFromOffer(offer, temporaryID)) {
                            return foundFromOffer
                        }
                    }  
                }   
            }
        }
    }

    findFromOffer(offer, temporaryID) 
    {
        /**
         * NOTE: offer.options.customFilteredItemsColumn might be undefined on older coupons so lets ignore it
         */
        if (offer.type === 'Discount' && offer.options.customFilteredItemsColumn) {
            // customFilteredItemsColumn its a row here in the client (a column in the server)
            const selfFinder = new RowsComponentsFinder([offer.options.customFilteredItemsColumn])

            const founditem = selfFinder.find(temporaryID)

            if (founditem) {
                return founditem
            }
        }
    }
}