import { send_data, show_message } from '~/hooks/utils'
import useState from '~/hooks/useState'
import { MessageType} from '~/typs'
import 'toastify-js/src/toastify.css'
import { DateTime } from 'luxon'

export const format_date = (ndate: number):string => {
	let value = ''
	try {
		const d = new Date(ndate);
		value = d.toLocaleString();
	} catch(e) {
		console.log(`error date to string ${ndate}`)
	}
	return value
}
export const utf8_to_b64 = (str: string):string => {
  return window.btoa(unescape(encodeURIComponent( str )));
}

export const b64_to_utf8 = (str: string):string => {
  return decodeURIComponent(escape(window.atob( str )));
}
export const generate_uuid = ():string => {
  let dt = new Date().getTime()
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
     const r = (dt + Math.random()*16)%16 | 0;
     dt = Math.floor(dt/16);
     return (c=='x' ? r :(r&0x3|0x8)).toString(16);
  })
}
export const generate_value = (gen: string, val: string):string => {
	switch (gen) {
		case 'uuid': 
			return generate_uuid()
		case 'NowSet':
			const now = DateTime.now().toUTC()
			if (val === '?') {
				return now.toISO()
			} else if (val.endsWith('d')) {
				const num = parseInt(val.replace('?', '').replace('d', '')) || 0
				return now.plus({days: num}).toISO()
			} else if (val.endsWith('h')) {
				const num = parseInt(val.replace('?', '').replace('h', '')) || 0
				return now.plus({hours: num}).toISO()
			} else if (val.endsWith('m')) {
				const num = parseInt(val.replace('?', '').replace('m', '')) || 0
				return now.plus({minutes: num}).toISO()
			}
		default:
	    return val ? val : ''
	}
}
export const email_info = async(src: string, defs: any, key: string, data: any, msg: string) => {
	switch (src) {
		case 'invitations':
			const url = useState().CONFURLS.value.sendinvitation || ''
			if (url.length > 0) {
				const [res, err] = await send_data(url, { id: key, data }, true, true, () => {
					show_message(MessageType.Success,`${msg} sent`, 2000)
				})
				if (err && err.length > 0 && res && res.status && res.status !== 'ok') {
					show_message(MessageType.Error, `Error: ${err}`, 2000)
				}
			}
			break
	}
}
export default {
	format_date,
	utf8_to_b64,
	b64_to_utf8,
	generate_uuid,
	generate_value,
}
