import { Router } from 'express';
import { TEXT_CONSTANTS } from '../constants';
import { Exchange } from '../models_nosql';
import {
	getArraySortedByProp,
	startHandlerAllTickers,
	getTimestamps,
} from '../common';
import {
	startWebSocket,
	prefixes,
	getFundingRates,
	getListSymbols,
	getAllRatesArray,
} from '../utilities';

export const additionalsRouter = Router();

// start screener'ов
additionalsRouter.get('/start-screener', async (req, res) => {
	// const { userId } = req.body;
	// const user = await User.findOne({ _id: userId });
	let message = 'Screener started!';
	let success = true;
	
	const startTime = getTimestamps();
	const stTm = new Date();
	await startHandlerAllTickers({ typeMarket: 'SPOT' });
	await startHandlerAllTickers({ typeMarket: 'FUT' });
	const endTime = getTimestamps();
	const edTm = new Date();
	const diff = (edTm - stTm) / (1000 * 60);
	console.log(
		` 0_Time: ${startTime} \n 1_Time: ${endTime} \n result: ${diff.toFixed(
			2
		)} minutes`
	);

	return res.status(200).send({
		message,
		success,
	});
});

// start websocket'ов
additionalsRouter.get('/start-websocket', async (req, res) => {
	let message = 'WebSocket started!';
	let success = true;

	for (let i = 0; i < prefixes.length; i++) {
		startWebSocket(prefixes[i]);
	}

	return res.status(200).send({
		message,
		success,
	});
});

// получение fundingRates
additionalsRouter.post('/get-funding-rates', async (req, res) => {
	const { userId } = req.body;
	const user = await User.findOne({ _id: userId });

	// const rates = await getFundingRates({ user: {}, prefix: 'ALL_API' });
	// const ratesBT = await getFundingRates({ user, prefix: 'BT_API' });
	// const ratesGT = await getFundingRates({ user: {}, prefix: 'GT_API' });
	const rates = [];
	const ratesBT = [];
	const ratesGT = [];
	// console.log(ratesGT[0]);
	const configMG = {
		userId: '****dbb3',
		prefix: 'MG',
		config: {
			withCredentials: true,
			method: 'GET',
			url: 'https://contract.mexc.com/api/v1/contract/detail',
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
			},
		},
	};

	const ratesMG = [];
	const symbols = await getListSymbols(configMG);
	// console.log(symbols)
	// let count = 0;
	// for (let i = 0; i < symbols.length; i++) {
	// 	const result = await getFundingRates({
	// 		user: {},
	// 		prefix: 'MG',
	// 		symbol: symbols[i].symbol,
	// 	});
	// 	ratesMG.push(result);
	// 	console.log(count++, symbols[i].symbol);
	// 	console.log(symbols[i]);
	// }

	const prms = [
		{ exchange: 'Bybit', prefix: 'BT', rates: ratesBT },
		{ exchange: 'MexcGlobal', prefix: 'MG', rates: ratesMG },
		{ exchange: 'Gate', prefix: 'GT', rates: ratesGT },
	];

	const allRates = getAllRatesArray(rates, prms);
	// console.log(allRates[0].uMarginList);

	const message =
		rates.length === 0 ? 'getFundingRates Error!' : 'getFundingRates Ok!';
	const success = rates.length === 0 ? false : true;

	return res.status(200).send({
		message,
		data: allRates,
		success,
	});
});
