import { CONTRACT } from '../../../../'
import CI = CONTRACT.CONTRACT_INTERFACES
import queryChainContract = CONTRACT.CONTRACT_TOOLS.queryChain

const getAllStillNotClosedLatestIdeas = (
	cachedStrategyState: CI.IStrategyState,
): CI.ITradeIdea[] => {
	const allOrderedIdeas = queryChainContract.getAllIdeas(cachedStrategyState)
	const stillNotClosedLatestIdeas = new Map<number, CI.ITradeIdea>()
	const stillNotClosedList = new Set<number>()
	for (const idea of allOrderedIdeas) {
		if (typeof idea.idea === 'string') {
			stillNotClosedList.add(idea.content.ideaKey!)
			stillNotClosedLatestIdeas.set(idea.content.ideaKey!, idea)
		} else {
			if (idea.idea.kind !== 'close') {
				stillNotClosedList.add(idea.content.ideaKey!)
				stillNotClosedLatestIdeas.set(idea.content.ideaKey!, idea)
			} else {
				stillNotClosedList.delete(idea.content.ideaKey!)
				stillNotClosedLatestIdeas.delete(idea.content.ideaKey!)
			}
		}
	}
	return Array.from(stillNotClosedLatestIdeas.values())
}

export const querychain = {
	...queryChainContract,
	getAllStillNotClosedLatestIdeas,
}
