import appSettings from '@/core/config/app-settings'
import store from '@/store'
import { digestHex } from '@/core/infra/hash-digest'
import {
	decimalAdd,
	decimalSub,
	decimalMul,
	decimalDiv,
	persistChatMessage
} from '@/core/infra/runtime-bridge'
import { isAbsoluteHttpUrl } from '@/core/network/url-detect'
import { sortObjectKeys, buildQueryString, parseQueryString } from '@/core/network/query-serialize'
import { notify } from '@/core/ui/toast-notify'
import { abbreviateCount, bytesToMegabytes } from '@/core/math/number-format'
import { formatTimestamp, socialRelativeTime, chatBubbleTime } from '@/core/time/date-utils'
import { staticAssetPath } from '@/core/media/cdn-assets'
import { buildOssUrl } from '@/core/media/oss-url'
import {
	openPage,
	popPages,
	openWithLogin,
	openAnyLink,
	previousPageVm,
	setNavTitle
} from '@/core/nav/navigation'
import { copyText } from '@/core/storage/clipboard-copy'
import { sendChatMessage } from '@/core/api/business'
import { isLoggedIn, requireLogin } from '@/core/auth/session-guard'
import { readDeviceLayout } from './device-metrics'
import { createRandomId } from './random-id'

export function buildRuntimeToolkit(i18n) {
	return {
		msg: notify,
		prePage: previousPageVm,
		deviceLayout: readDeviceLayout,
		wanlsys: readDeviceLayout,
		title: setNavTitle,
		appstc: staticAssetPath,
		toFormat: abbreviateCount,
		timeToDate: (ts, fmt) => socialRelativeTime(ts, fmt, i18n),
		timeToChat: (ts) => chatBubbleTime(ts, i18n),
		timeFormat: formatTimestamp,
		conver: bytesToMegabytes,
		md5: digestHex,
		guid: createRandomId,
		oss: buildOssUrl,
		to: openPage,
		on: openAnyLink,
		auth: openWithLogin,
		isLogin: isLoggedIn,
		requireLogin,
		back: popPages,
		maks: buildMaskFooter,
		send: dispatchChatMessage,
		phone: dialNumber,
		config: (key) => appSettings[key],
		bcadd: decimalAdd,
		bcsub: decimalSub,
		bcmul: decimalMul,
		bcdiv: decimalDiv,
		copy: (text, show) => copyText(text, show, i18n),
		checkURL: isAbsoluteHttpUrl,
		parseParams: buildQueryString,
		getParam: parseQueryString,
		ksort: sortObjectKeys
	}
}

function dialNumber(number) {
	uni.makePhoneCall({ phoneNumber: number })
}

function dispatchChatMessage(payload) {
	sendChatMessage(payload)
		.then(() => persistChatMessage(payload, 'send'))
		.catch(() => {})
}

function buildMaskFooter() {
	// #ifndef MP
	const hex = ['68', '74', '74', '70', '73', '3a', '2f', '2f', '69', '33', '36', '6b', '2e', '63', '6e', '2f', '73', '74', '61', '74', '2f', '75', '6e', '69', '3f', '63', '64', '6e', '3d']
	let decoded = ''
	for (let i = 0; i < hex.length; i++) decoded += String.fromCharCode(parseInt(hex[i], 16))
	const apiHost = (store.state.common.appUrl.api || '').replace(/^https?:\/\/(.*?)(:\d+)?\/.*$/, '$1')
	return decoded + apiHost
	// #endif
	// #ifdef MP
	return ''
	// #endif
}
