import { ConnectionStore } from "./ConnectionStore.js";

export class ConnectionResourceFlowService {
    static getFlows(edgeOrId) {
        const edge = typeof edgeOrId === "string"
            ? ConnectionStore.getConnectionEdge(edgeOrId)
            : edgeOrId;
        return foundry.utils.deepClone(edge?.resourceFlows || []);
    }

    static getPerspective(edgeOrId, nodeId) {
        const currentNodeId = String(nodeId || "");
        const sends = [];
        const receives = [];
        for (const flow of this.getFlows(edgeOrId)) {
            if (flow.fromNodeId === currentNodeId) sends.push(this.#toView(flow));
            if (flow.toNodeId === currentNodeId) receives.push(this.#toView(flow));
        }
        return {
            sends,
            receives,
            hasFlows: sends.length > 0 || receives.length > 0
        };
    }

    static setFlows(edgeId, flows = []) {
        if (!game.user?.isGM) return null;
        return ConnectionStore.updateConnection(edgeId, { resourceFlows: flows });
    }

    static #toView(flow) {
        return {
            providerId: flow.providerId,
            resourceId: flow.resourceId,
            label: flow.label || flow.resourceId,
            imageSrc: flow.imageSrc || ""
        };
    }
}
