import {request} from '../../../fetch-request'
import {deleteTradeOffer, signTradeBotTxn} from '../../../tradeRequest'
import {processTransaction} from '../../../createTransaction'

export const cancelAllOffers = async (requestObject) => {
	const keyPair = requestObject.keyPair
	const publicKey = requestObject.base58PublicKey
	const address = requestObject.address

	const getMyOpenOffers = async () => {
		const res = await request('/crosschain/tradeoffers')
		return await res.filter(order => order.mode === "OFFERING" && order.qortalCreator === address)
	}

	const myOpenOffers = await getMyOpenOffers()

	let response = true

	myOpenOffers.forEach(async (openOffer) => {
		let unsignedTxn = await deleteTradeOffer({ creatorPublicKey: publicKey, atAddress: openOffer.qortalAtAddress })
		let signedTxnBytes = await signTradeBotTxn(unsignedTxn, keyPair)
		await processTransaction(signedTxnBytes)
	})

	return response
}
