import api from '@/api/api.js'
import sortObj from '@/utils/sort'
import version from '@/utils/version.js'
import client_type from '@/utils/client_type.js'
import { Base64 } from 'js-base64'
import { md5 } from 'js-md5'

function formatString(obj) {
	let concatenated = ''
	for (const key in obj) {
		if (concatenated) {
			concatenated += key + obj[key]
		} else {
			concatenated = key + obj[key]
		}
	}
	return concatenated
}

function toBase64Url(str) {
	return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '')
}

export async function createSignedPostData(extraData = {}) {
	try {
		const res = await api.getTimeStamp()
		const timestamp = res.data.timestamp.toString()
		const basePayload = {
			version: version,
			user_uuid: '',
			client_type: client_type,
			timestamp: timestamp
		}
		const postData = { ...basePayload, ...extraData }
		const sorted = sortObj(postData)
		const str1 = formatString(sorted).replace(' ', '')
		const str2 = str1 + md5(timestamp)
		const str3 = md5(str2)
		const sign = toBase64Url(Base64.encode(str3))
		return { postData, sign }
	} catch (err) {
		console.log(err)
		return { postData: {}, sign: '' }
	}
}

export default { createSignedPostData }


