import {TreeNode} from "../TreeNode";
import {CloneTierAction} from "./interfaces";
import {NestedTestableNodeData} from "../InMemoryTestableNode";
import {NestedBranchData} from "../MemoryBranchNode";
import {OfferData} from "../store";
import {TieredExtraData} from "../StateBranchNode";
import {DiscountMeta, DiscountOptions} from "../cards/Discount";
import {removeIds} from "../NodeHelpers";
import {cloneDeep} from "lodash";
import {StateObjects} from "../Grove";

export class OffersBranchCloner implements CloneTierAction {
    constructor(
        private stateObjects: Pick<StateObjects, 'testables'>
    ) {
    }
    canCloneTier(treeNode: TreeNode): boolean {
        return treeNode.branchNode.isOffers()
    }

    // @ts-ignore
    cloneTier(nestedTestableNodeData: NestedTestableNodeData, nestedBranchData: NestedBranchData<OfferData, TieredExtraData>) {
        // first make sure we remove the ids from all offers so that they are added to the state as new offers (new ids will be generated somewhere else)
        nestedBranchData.children.forEach(offer => {
            // @ts-ignore
            delete offer.id
        })
        // remove the ids from the discounts that have the customfiltereditems option so that they are added
        // to the state when adding this tree node to the grove.
        const discounts = nestedBranchData.children.filter(offer => offer.type === DiscountMeta.id)

        console.log('discounts: ', discounts)
        discounts.forEach(discount => {
            const options: DiscountOptions = cloneDeep(discount.options) as DiscountOptions

            discount.options = {
                ...options,
                customFilteredItemsSourceMap: removeIds(
                    // we're getting a string so just for now let's query the testable from the state (might refactor in the future)
                    this.stateObjects.testables.getNodeWithChildren(options.customFilteredItemsSourceMap as string || '') || ''
                )
            }
            console.log('discoun options: ', discount.options)
        })

    }
}