import axios from 'axios';
import {
	getTimestamps,
	getSingleUserProperty,
	getObjectRequestParams,
} from '../common';
import { CONSTANTS_BT } from '../constants';

// получение funding rates by API from coinglass.com
// https://coinglass.readme.io/reference/funding-rate
// https://docs.coinglass.com/reference/fr-exchange-list
export const getFundingRates = async (params) => {
	const { user, prefix, symbol } = params;
	let result = [];
	const config = {
		withCredentials: true,
		method: 'GET',
		// url: 'https://open-api.coinglass.com/public/v2/funding',
		url: 'https://open-api-v3.coinglass.com/api/futures/fundingRate/exchange-list',
		data: null,
		headers: {
			'access-control-allow-credentials': true,
			'Access-Control-Allow-Origin': '*',
			'content-type': 'application/json;charset=UTF-8',
		},
	};

	if (prefix === 'ALL_API') {
		// config.headers.coinglassSecret = '2585aea307e849bfbaa40064554bd97a';
		config.headers['CG-API-KEY'] = '2585aea307e849bfbaa40064554bd97a';
	} else if (prefix === 'MG') {
		config.url = `https://contract.mexc.com/api/v1/contract/funding_rate/${symbol}`;
	} else if (prefix === 'BT_API') {
		const objParamsTickers = {
			userId: user._id,
			shortName: 'BT',
			prefix: `fut_tickers_BT_API`,
			constants: CONSTANTS_BT,
			apiKeys: getSingleUserProperty('apiKeys', 'Bybit', user.properties),
			requestHeader: {},
			additionals: {},
		};
		const objReqParams = getObjectRequestParams(objParamsTickers);
		config.method = objReqParams.config.method;
		config.url = objReqParams.config.url;
		config.headers = objReqParams.config.headers;
	} else if (prefix === 'GT_API') {
		// https://www.gate.io/docs/developers/apiv4/en/#list-all-futures-contracts
		config.url = `https://api.gateio.ws/api/v4/futures/usdt/contracts`;
	}

	await axios(config)
		.then((response) => {
			if (prefix === 'ALL_API') {
				console.log(response.data.data);
				// result = response.data.msg === 'success' ? response.data.data : [];
			} else if (prefix === 'MG') {
				result = response.data.success ? response.data.data : [];
			}
			else if (prefix === 'BT_API') {
				result =
					response.data.retMsg === 'OK' ? response.data.result.list : [];
			} else if (prefix === 'GT_API') {
				// console.log(response.data);
				result = response.data;
			}
		})
		.catch((error) => {
			console.log(
				`${prefix}=======// ${getTimestamps()} //=======\ngetFundingRates request Error!\n${error}`
			);
		});

	return result;
};

// получение списка тикеров
export const getListSymbols = async (params) => {
	let result = [];
	const { userId, prefix, config } = params;
	// prefix === 'BT_API' ? console.log(params) : null;
	await axios(config)
		.then((response) => {
			// prefix === 'GX_API' ? console.log(response.data) : null;
			if (prefix === 'MG') {
				result = response.data.success ? response.data.data : [];
			} else if (prefix === 'BT') {
				// console.log(response.data);
				result =
					response.data.ret_msg === 'success'
						? response.data.result.LinearPerpetual
						: [];
			} else if (prefix === 'BT_API') {
				// console.log(response.data);
				result =
					response.data.retMsg === 'OK' ? response.data.result.list : [];
			}
		})
		.catch((error) => {
			console.log(
				`=======// ${getTimestamps()} //=======\n****${userId.slice(
					-4
				)} | ${prefix}: ${TEXT_CONSTANTS.SPOT_ORDERS_ER}\n${error}`
			);
		});
	return result;
};

// изменение неполных - BT, GT и добавление новых - MG, KC
export const getAllRatesArray = (allRates, params) => {
	for (let k = 0; k < params.length; k++) {
		const rates = params[k].rates;
		const prefix = params[k].prefix;
		const name = params[k].exchange;

		for (let i = 0; i < allRates.length; i++) {
			// фильтруем по совпадению символов
			const symbolFiltred = rates.filter((item) => {
				const postfix = prefix === 'BT' ? 'USDT' : '_USDT';
				const symbol =
					prefix === 'BT' || prefix === 'MG' ? item.symbol : item.name;
				return allRates[i].symbol + postfix === symbol;
			});
			// console.log(symbolFiltred.length);
			if (symbolFiltred.length === 0) {
				const newSymbol = {
					symbol: 'BTC',
					symbolLogo:
						'https://cdn.coinglasscdn.com/static/img/coins/bitcoin-BTC.png',
					status: 0,
					uMarginList: [
						{
							rate: 0.008493,
							predictedRate: 0,
							exchangeLogo:
								'https://cdn.coinglasscdn.com/static/exchanges/270.png',
							exchangeName: 'Binance',
							status: 1,
							nextFundingTime: 1694822400000,
						},
					],
					cMarginList: [],
					uIndexPrice: 26369.25065934,
					uPrice: 26359.2,
					cIndexPrice: 26371.73107656,
					cPrice: 26357.1,
				};
				const itemBT = {
					symbol: '10000LADYSUSDT',
					bidPrice: '0.0003890',
					askPrice: '0.0003895',
					lastPrice: '0.0003890',
					lastTickDirection: 'ZeroMinusTick',
					prevPrice24h: '0.0003135',
					price24hPcnt: '0.240829',
					highPrice24h: '0.0003910',
					lowPrice24h: '0.0003070',
					prevPrice1h: '0.0003710',
					markPrice: '0.0003895',
					indexPrice: '0.0003878',
					openInterest: '12536360500',
					turnover24h: '10885790.7655',
					volume24h: '30693967200.0000',
					fundingRate: '0.000534',
					nextFundingTime: '1694822400000',
					predictedDeliveryPrice: '',
					basisRate: '',
					deliveryFeeRate: '',
					deliveryTime: '0',
					openInterestValue: '4882912.41',
				};
				const itemMG = {
					symbol: 'BTC_USDT',
					fundingRate: 0.000055,
					maxFundingRate: 0.002,
					minFundingRate: -0.002,
					collectCycle: 8,
					nextSettleTime: 1694822400000,
					timestamp: 1694805833365,
				};
			}
			// если символ нашелся
			else {
				const marginList = allRates[i].uMarginList.slice();
				// обновляем nextFundingTime
				allRates[i].uMarginList = handlerMarginList(
					marginList,
					symbolFiltred[0],
					name
				);
			}
		}
	}

	return allRates;
};

// обработчие обновления nextFundingTime
const handlerMarginList = (marginList, filtredSymbol, exchange) => {
	if (exchange === 'Bybit') {
		for (let i = 0; i < marginList.length; i++) {
			if (marginList[i].exchangeName === exchange) {
				marginList[i].nextFundingTime = filtredSymbol.nextFundingTime;
			}
		}
	} else if (exchange === 'Gate') {
		for (let i = 0; i < marginList.length; i++) {
			if (marginList[i].exchangeName === exchange) {
				marginList[i].nextFundingTime =
					Date.now() + filtredSymbol.funding_interval * 1000;
			}
		}
	} else if (exchange === 'MexcGlobal') {
		const newItem = {
			rate: +filtredSymbol.fundingRate * 100,
			predictedRate: 0,
			exchangeLogo: '',
			exchangeName: exchange,
			status: 1,
			nextFundingTime: filtredSymbol.nextSettleTime,
		};
		marginList.push(newItem);
	}
	return marginList;
};
