import 'isomorphic-fetch'

import {
	IActivDirectSearchAssetParams,
	ILitAction,
	CONTRACT_INTERFACES,
} from '../../..'

export const IG_PRE_AUTHENTICATE = async (
	key: string, // api key
	secret: string, // username
	secret2: string, // password
): Promise<{
	key: string // api key
	secret: string // cst
	secret2: string // x-security-token
}> => {
	const environment = 'production' as string

	const url =
		environment === 'demo'
			? 'https://demo-api.ig.com'
			: 'https://api.ig.com'

	const fetcherOptionHeaders = {
		url: `${url}/gateway/deal/session?fetchSessionTokens=true`,
		method: 'POST',
		headers: {
			'Content-Type': 'application/json; charset=UTF-8',
			Accept: 'application/json; charset=UTF-8',
			'X-IG-API-KEY': key,
			Version: '2',
		},
		body: JSON.stringify({
			identifier: secret,
			password: secret2,
		}),
		redirect: 'follow',
		mode: 'cors',
	}

	try {
		// console.log('IG_PRE_AUTHENTICATE (fetcherOptionHeaders)', fetcherOptionHeaders)

		const response = await fetch(
			fetcherOptionHeaders.url,
			fetcherOptionHeaders as unknown as RequestInit,
		)

		const clientSessionToken = response.headers.get('cst')

		const activeAccountSessionToken =
			response.headers.get('x-security-token')

		// console.log('IG_PRE_AUTHENTICATE (key)', key)
		// console.log('IG_PRE_AUTHENTICATE (clientSessionToken)', clientSessionToken)
		// console.log('IG_PRE_AUTHENTICATE (activeAccountSessionToken)', activeAccountSessionToken)

		if (!clientSessionToken || !activeAccountSessionToken) {
			throw new Error('Failed to get tokens')
		}

		return {
			key,
			secret: clientSessionToken,
			secret2: activeAccountSessionToken,
		}
	} catch (err) {
		throw new Error(
			'Could not get IG authentication: ' +
				((err as any).message || JSON.stringify(err)),
		)
	}
}

const testPricing = async (
	params: IActivDirectSearchAssetParams,
): Promise<CONTRACT_INTERFACES.IPrice> => {
	// console.log('params')
	// console.log(params)
	const { secret, secret2 } = await IG_PRE_AUTHENTICATE(
		params.key!,
		params.secret!,
		params.secret2!,
	)

	// console.log('key')
	// console.log(params.key!)
	// console.log('secret')
	// console.log(secret)
	// console.log('secret2')
	// console.log(secret2)

	const headers = {
		'User-Agent': 'Request-Promise',
		Accept: 'application/json; charset=UTF-8',
		'Content-Type': 'application/json; charset=UTF-8',
		CST: secret,
		VERSION: '3',
		'X-IG-API-KEY': params.key!,
		'X-SECURITY-TOKEN': secret2,
	}
	const environment = 'production' as string
	const baseUrl =
		environment === 'demo'
			? 'https://demo-api.ig.com/gateway/deal'
			: 'https://api.ig.com/gateway/deal'
	const requestRecipe = {
		url: `${baseUrl}/markets/${params.symbol}`,
		method: 'GET',
		headers,
		redirect: 'follow',
		mode: 'cors',
	}

	const result = await fetch(
		requestRecipe.url,
		requestRecipe as unknown as RequestInit,
	).then((res) => res.json())
	//console.log('response:')
	//console.log(response)
	const data = result.snapshot

	if (data === null || data === undefined) {
		throw new Error('Price could not be retrieved')
	}

	if (data.marketStatus !== 'TRADEABLE') {
		throw new Error('Market Closed!')
	}

	// must be alphabetical order
	// const globalPrice = parseFloat(data.price);
	let ask = data.offer
	let bid = data.bid
	ask = ask / data.scalingFactor
	bid = bid / data.scalingFactor
	let globalPrice = (ask + bid) / 2
	let decimals = data.decimalPlacesFactor
	decimals = decimals + Math.floor(Math.log10(data.scalingFactor))
	globalPrice = parseFloat(globalPrice.toFixed(decimals))
	const timestamp = Date.now()
	// console.log('timestamp:')
	// console.log(timestamp)
	const priceObj: CONTRACT_INTERFACES.IPrice = {
		ask,
		bid,
		globalPrice,
		provider: 'IG Group',
		symbol: params.symbol,
		timestamp,
	}

	return priceObj
}

/*
	Final action:
	Network: Lit Chronicle
	Onwer Account Wallet: FIRED! => Mint&Grant&Burned! => SECURED!
	PKP id: 74197395819624550604773903670852859171002951156985493098804192391758725613755
	PKP public key: 0x049f1cb2ddb5d989e0b335d957400ae9c06acef99b879d3757b57b17086c2e807a93d62f993abb6b9cd07a4bb7cf66a7df45c9de7b88ff7a94c18cd579bdfc8f85
	PKP ETH: 0xe24698d197107cFF37E991e471655Cb3be05Ed8E
	Action ipfsId: QmaJ4qhDGVGC9otQqkbhnDPfmpjQEazWWbxErQwRqcUSmA
	granted?: true
*/
export const GET_PRICE_IG_V2: ILitAction = {
	ipfsId: 'QmaJ4qhDGVGC9otQqkbhnDPfmpjQEazWWbxErQwRqcUSmA',
	publicKey:
		'0x049f1cb2ddb5d989e0b335d957400ae9c06acef99b879d3757b57b17086c2e807a93d62f993abb6b9cd07a4bb7cf66a7df45c9de7b88ff7a94c18cd579bdfc8f85',
	keyEthAddress: '0xe24698d197107cFF37E991e471655Cb3be05Ed8E',
	testPricing,
}
