import {ExportImportTarget, StoreExporter} from "./Exporters";
import {FullState, Grove} from "../Grove";
import {ExportableDataFormatPreset} from "./AppImporter";
import {TreeNode} from "../TreeNode";
import {Testables} from "../testables";
import testable from "../../Testable";

export class GroveExporter implements StoreExporter {
    grove: Grove;
    private testables: Testables;
    constructor(protected store: FullState)  {
        const {grove, testables} = Grove.fromState(store, true);
        this.grove = grove;
        this.testables = testables;
    }

    export(target: ExportImportTarget): string {
        return JSON.stringify(this.exportAsData(target));
    }

    exportAsData(target: ExportImportTarget): ExportableDataFormatPreset['grove'] {
        return this.grove.getTrees().map((treeNode: TreeNode) => {
            return this.exportTreeNode(treeNode, target)
        })
    }

    exportTreeNode = ({branchNode, testableNode, suggestedScope}: TreeNode, target: ExportImportTarget) => {
        return {
            // @ts-ignore
            testable: testableNode.exportData(target, this),
            /**
             * Here we might need to change the branch type (I believe tiers aren't recognized as such in the backend, but let's get simple offers branch for now...)
             */
            branch: branchNode.exportData(target, this),
            extraData: {
                suggestedScope,
            }
        };
    }
}