import $ from "jquery"
import {
	CONSTANTS,
	CONSTANTS_STORAGE,
	EXCHANGE_ICON_URL,
	PAY_ICON_URL,
	CURRENCY_ICON_URL,
} from "../constants"

// Извлечение Данных из LocalStorage
export const getDataFromLocalStorage = (nameStorage: string) => {
	let dataLocalStorage = null
	const ls: null | string = localStorage.getItem(nameStorage)
	if (typeof ls === "string") dataLocalStorage = JSON.parse(ls)

	return dataLocalStorage
}

const dataConstants = getDataFromLocalStorage(CONSTANTS_STORAGE)
const EXCHANGES =
	dataConstants === null
		? CONSTANTS.ARRAY_EXCHANGES
		: dataConstants.exchanges
const PAYTYPES = dataConstants === null ? [] : dataConstants.payTypes
const CURRENCIES = dataConstants === null ? [] : dataConstants.currencies

// Сохранение данных в LocalStorage
export const saveDataToLocalStorage = (
	nameLocalStorage: string,
	valueLocalStorage: any
) => {
	localStorage.setItem(nameLocalStorage, JSON.stringify(valueLocalStorage))
}

// Удаление данных user'a из LocalStorage
export const removeDataFromLocalStorage = (nameLocalStorage: string) => {
	localStorage.removeItem(nameLocalStorage)
}

// Извлечение даты и времени из stampstring
export const getTimeDate = (time: any) => {
	const myDate = new Date(time).toLocaleString()
	const remarkedTime = myDate.replaceAll(".", "-")
	return remarkedTime.replace(",", " ")
}

// кроссбраузерное получение localDate
export const getLocalDate = () => {
	return new Date(new Date().getTime()).toLocaleString("ru", {
		year: "numeric",
		month: "numeric",
		day: "numeric",
	})
}

// приведение строки к маске числа 000,000,000.00
export const getPriceMasked = (price: any): number => {
	const priceMasked: any = parseFloat(price)
		.toFixed(2)
		// .replace(/\d(?=(\d{3})+\.)/g, "$&,")
		.replace(".", ",")
	return priceMasked
}

// получение стоимости актива в USDT по текущемку курсу
export const getValuationUSDT = (
	coursesArray: any,
	assetName: string,
	assetVolume: any
) => {
	let result: any = +assetVolume * 1
	if (
		Array.isArray(coursesArray) &&
		coursesArray.length !== 0 &&
		assetName
	) {
		const tickerName =
			assetName === "DAI" ||
			assetName === "RUB" ||
			assetName === "UAH" ||
			assetName === "HUSD"
				? "USDT" + assetName
				: assetName + "USDT"
		for (let i = 0; i < coursesArray.length; i++) {
			if (coursesArray[i].ticker === tickerName) {
				if (
					tickerName === "USDTDAI" ||
					tickerName === "USDTRUB" ||
					tickerName === "BUSDRUB" ||
					tickerName === "USDTUAH" ||
					tickerName === "USDTHUSD"
				) {
					result = +assetVolume / +coursesArray[i].course
				} else {
					result = +assetVolume * +coursesArray[i].course
				}
			}
		}
	}
	return parseFloat(result).toFixed(2)
}

// фильтрация массива валют по доступности на текущей бирже
export const getArrayCurrenciesFiltered = (
	exchangeId: string,
	typeCurrency: string
) => {
	const arrayCurrecies: any = []
	for (let i = 0; i < CURRENCIES.length; i++) {
		if (CURRENCIES[i].currencyType === typeCurrency) {
			// FilterUserReports
			if (exchangeId === "All") {
				arrayCurrecies.push({
					currency: CURRENCIES[i].currency,
					iconUrl: CURRENCY_ICON_URL + CURRENCIES[i].iconUrl,
				})
			} else {
				const props = CURRENCIES[i].currencyProps.slice()
				for (let j = 0; j < CURRENCIES[i].currencyProps.length; j++) {
					if (
						props[j].switchedOn === true &&
						props[j].exchangeId === exchangeId
					) {
						arrayCurrecies.push({
							currency: CURRENCIES[i].currency,
							iconUrl: CURRENCY_ICON_URL + CURRENCIES[i].iconUrl,
						})
					}
				}
			}
		}
	}
	return arrayCurrecies
}

// сортировка любого массива по возрастанию/убыванию by propName
export const getArraySortedByProp = (
	propName: string,
	arr: any,
	flagName?: string
) => {
	const arrayOrders = arr.sort((a: any, b: any) => {
		if (propName === "dateOrder") {
			if (Number(a[propName]) > Number(b[propName])) return -1
			if (Number(a[propName]) < Number(b[propName])) return 1
		} else {
			if (a[propName] < b[propName]) return -1
			if (a[propName] > b[propName]) return 1
		}
		return 0
	})
	return arrayOrders
}

// func скрытия всплывшего алерта по типу toast materializecss
export const startModalAlert = () => {
	const nameElem = "#modal-alert"
	$(nameElem).modal("show")
	const timerId = setTimeout((): void => {
		$(nameElem).modal("hide")
	}, 3000)
	return () => clearTimeout(timerId)
}

// Переключатель фона модулей exchanges
export const changeBackgroundBody = (backgroundURL: string) => {
	$("body").css({ backgroundImage: `url(${backgroundURL})` })
}

// Извлечение url иконки или названия криптовалюты и Вида платежа
export const getUrlIcon = (typeIcon: string, nameParam: string) => {
	let item = ""
	if (typeIcon === "FiatSymbol") {
		for (let i = 0; i < CURRENCIES.length; i++) {
			if (
				CURRENCIES[i].currencyType === "fiat" &&
				CURRENCIES[i].currency === nameParam
			)
				item = CURRENCIES[i].symbol
		}
	} else if (typeIcon === "logoExchange") {
		for (let i = 0; i < EXCHANGES.length; i++) {
			if (EXCHANGES[i].shortName === nameParam)
				item = EXCHANGE_ICON_URL + EXCHANGES[i].logo
		}
	} else if (typeIcon === "iconPaymentByID") {
		for (let i = 0; i < PAYTYPES.length; i++) {
			if (PAYTYPES[i].id === nameParam) {
				item = PAY_ICON_URL + PAYTYPES[i].iconUrlColor
			}
		}
	} else if (typeIcon === "iconCurrencyByName") {
		for (let i = 0; i < CURRENCIES.length; i++) {
			if (CURRENCIES[i].currency === nameParam) {
				item = CURRENCY_ICON_URL + CURRENCIES[i].iconUrl
			}
		}
	}
	return item
}

// универсальный валидатор отдельного поля формы addUser, editUser, resetPass
export const isValideField = (nameId: string, pattern: any) => {
	const elem = $("#" + nameId)
	const elemValue = elem.val()

	// если pattern установлен, проверяем регулярку
	if (pattern) {
		// console.log(pattern.test(elemValue))
		const res = pattern.test(elemValue)

		if (!res) elem.removeClass("is-valid").addClass("is-invalid")
		else elem.removeClass("is-invalid").addClass("is-valid")
	}
	// если pattern не установлен, проверяем пустой ли input
	else {
		if (elemValue === "") elem.removeClass("is-valid").addClass("is-invalid")
		else elem.removeClass("is-invalid").addClass("is-valid")
	}
}

// получение массива IDs merchant-ордеров
export const getArrayMerchantOrderIds = (exg: string, arrOrders: any) => {
	const result =
		arrOrders.length === 0 || arrOrders[0] === null
			? []
			: arrOrders.filter((item: any) => {
					return item.statusProps.value === "Completed"
			  })
	return result.map((item: any) => {
		return item.orderId
	})
}

// получение массива уникальных значений
export const getArrayUniqueValues = (objParams: {
	nameField: string,
	arrayItems: any,
}) => {
	const { nameField, arrayItems } = objParams
	const commonArray = []
	for (let i = 0; i < arrayItems.length; i++) {
		commonArray.push(arrayItems[i][nameField])
	}
	const uniqueItems = Array.from(new Set(commonArray))
	return uniqueItems
}

// Извлечение значение статуса ордера и класса на его подсветку
export const getColorValueStatus = (
	exchange: string,
	idOrderStutus: string
) => {
	const obj = { value: "", color: "" }
	const statusesArray = CONSTANTS.OTC_ORDER_STATUSES
	for (let i = 0; i < statusesArray.length; i++) {
		if (statusesArray[i].status === idOrderStutus) {
			obj.value = statusesArray[i].status
			obj.color = statusesArray[i].colorStatus
		}
	}
	return obj
}

// расчет себестоимости закупа USDT
export const getCostUSDT = (advPrice: number, priceUSDT: any) => {
	const calcSumm = 10000
	const volumeAsset = calcSumm / +advPrice
	const volumeUSDT = volumeAsset * +priceUSDT
	const costUSDT = calcSumm / volumeUSDT
	return costUSDT.toFixed(2)
}

// расчет суммарной стоимости баланса
export const getSummUSDT = (arr: any, flag: string) => {
	let result = 0
	const filtered =
		flag === "TZ"
			? arr.filter((item: any) => {
					return item.exchange === flag
			  })
			: arr
	for (let i = 0; i < filtered.length; i++) {
		// console.log(+filtered[i].summ)
		result += +filtered[i].summ
	}
	return result
}

// получение цены тикера из локального хранилища тикеров
export const handlerPriceTickers = (
	nameTicker: string,
	arrTickers: any
) => {
	let price = null
	if (nameTicker === "ETHWRUB") nameTicker = "ETHRUB"
	if (nameTicker === "DAIRUB" || nameTicker === "HUSDRUB")
		nameTicker = "USDTRUB"
	if (nameTicker === "RUBRUB") return (price = "1")
	for (let i = 0; i < arrTickers.length; i++) {
		if (arrTickers[i].ticker === nameTicker) price = arrTickers[i].course
	}
	// console.log(nameTicker)
	return price
}

// получение obj exchange по id биржи
export const getObjExchangeByExchangeId = (exchangeId: string) => {
	const objExchange = EXCHANGES.filter((item: any) => {
		return item.id === exchangeId
	})
	return objExchange[0]
}

// получение конкретного свойства user`a by ExchangeId
export const getUserPropertyByExchange = (
	nameProperty: string,
	exchange: string,
	arrayProperties: any
) => {
	let property = null
	if (
		nameProperty === "favorites" ||
		nameProperty === "favoriteAdvs" ||
		nameProperty === "payTypeList" ||
		nameProperty === "p2pOrders" ||
		nameProperty === "merchantOrders" ||
		nameProperty === "merchantPayMethods" ||
		nameProperty === "merchantAdvs"
	)
		property = []
	else if (nameProperty === "currentBalances")
		property = { p2pBalance: [], spotBalance: [], futBalance: [] }
	else if (nameProperty === "dateApiKeys") property = 0
	for (let i = 0; i < arrayProperties.length; i++) {
		if (
			arrayProperties[i].exchange === exchange ||
			arrayProperties[i].exchangeId === exchange
		) {
			for (const key in arrayProperties[i]) {
				if (key === nameProperty) property = arrayProperties[i][nameProperty]
			}
		}
	}
	return property
}

// получение obj UserProperties по name or id биржи
export const getUserPropsByExchange = (param: string, arrProps: any) => {
	const arrUserProps = arrProps.filter((item: any) => {
		return item.exchangeId === param || item.exchange === param
	})
	return arrUserProps[0]
}

// получение цены продажи USDT из объявления SELL USDT/RUB Binance
export const getSellingPriceUSDT = (advsArray: any): number => {
	let price = 0
	if (advsArray.length !== 0) {
		for (let i = 0; i < advsArray.length; i++) {
			if (
				advsArray[i].tradeType === "SELL" &&
				advsArray[i].asset === "USDT" &&
				advsArray[i].fiatUnit === "RUB"
			) {
				price = +advsArray[i].price
			}
		}
	}
	return price
}

// рассчет процента отклонения цены ордера от цены маркета
export const getPercent = (
	exchange: string,
	priceOrder: string,
	tradeType: string,
	priceAssetFiat: any,
	priceCurrencyUSDT: any
) => {
	// приводим к float типу
	const marketPrice: any =
		priceAssetFiat === null
			? parseFloat(priceCurrencyUSDT)
			: parseFloat(priceAssetFiat)
	const orderPrice: any = parseFloat(priceOrder)

	// процент оклонения от рыночной цены
	let percent = 0
	if (tradeType === "SELL") percent = (orderPrice * 100) / marketPrice - 100
	else percent = (marketPrice * 100) / orderPrice - 100
	return percent.toFixed(2)
}

// Дифф подсветка
export const getColorPurcent = (purcent: number) => {
	let colorPurcent = "text-success"
	if (purcent >= 93 && purcent < 97) colorPurcent = "text-warning"
	else if (purcent < 93) colorPurcent = "text-danger"
	return colorPurcent
}

// получение наименования тикера по asset/fiat/USDT
export const getTickerName = (
	field: string,
	asset: string,
	fiat: string
) => {
	let tickerName = asset + fiat
	if (field === "tickerAssetFiat") {
		if (
			(asset === "USDT" || asset === "BUSD") &&
			(fiat === "EUR" || fiat === "GBP")
		) {
			tickerName = fiat + asset
		}
	}
	// field === "tickerCurrencyUSDT"
	else {
		if (asset === "DAI" || asset === "RUB" || asset === "HUSD")
			tickerName = fiat + asset
	}
	return tickerName
}

// сброс/обработка подсветки активной кнопки
export const resetHighlightItem = (clickedElem: any, elems: any) => {
	for (let i = 0; i < elems.length; i++) {
		// удаляем .active со всех кнопок в группе
		$(elems[i]).removeClass(`active`)
	}
	// добавляем .active on element clicked
	$(clickedElem).addClass(`active`)
}

// Преобразовние к виду 1000 -> 1K
export const replace000ToK = (price: any) => {
	let result = price.toFixed(1)
	if (price >= 200 && price <= 1000000)
		result = (price * 0.001).toFixed(1) + "K"
	else if (price >= 1000000) result = (price * 0.000001).toFixed(1) + "M"
	return result
}

// Проверка наличия и включенности item currencyProps | payTypeProps
export const isSwitchedOnItem = (itemProps: any, exchangeId: string) => {
	const resultObj = { isExists: false, switchedOn: false }
	for (let i = 0; i < itemProps.length; i++) {
		if (itemProps[i].exchangeId === exchangeId) {
			resultObj.isExists = true
			resultObj.switchedOn = itemProps[i].switchedOn
		}
	}
	return resultObj
}

// switchON | OFF item currencyProps | payTypeProps
export const switcherHandlerItem = (
	itemProps: any,
	exchangeId: string
) => {
	const arr = itemProps.slice()
	for (let i = 0; i < arr.length; i++) {
		if (arr[i].exchangeId === exchangeId)
			// изменение switchedOn на противоположный
			arr[i].switchedOn = !arr[i].switchedOn
	}
	return arr
}
