// import store from '~/store'
import useState from '~/hooks/useState'
import { show_message, fetch_json } from '~/hooks/utils'
import { MessageType} from '~/typs'
import 'toastify-js/src/toastify.css'
import YAML from 'yaml'

export const set_config = (res: any) => {
	if (res && res.URLS && res.URLS.root) {
		Object.keys(res.URLS).forEach(it => {
			if (it === 'root' || res.URLS[it].includes('yaml') || res.URLS[it].includes('json') ) 
				useState().CONFURLS.value[it] = res.URLS[it]
			else 
		    useState().CONFURLS.value[it] = res.URLS.root.includes(':') ? `${res.URLS.root}${res.URLS[it]}` : res.URLS[it]
		})
	}
	if (res && res.ASSETS_PATH) 
		useState().ASSETS_PATH.value = res.ASSETS_PATH 
	if (res && res.DATA_PATH) 
		useState().DATA_PATH.value = res.DATA_PATH
	if (res && res.MODEL_ID) 
		useState().MODEL_ID.value = res.MODEL_ID
	if (res && res.URLKEY) 
		useState().URLKEY.value = res.URLKEY
	if (res && res.APPNAME) 
		useState().APPNAME.value = res.APPNAME
	if (res && res.APPHOME) 
		useState().APPHOME.value = res.APPHOME
	if (res && res.AUTHKEY) 
		useState().AUTHKEY.value = res.AUTHKEY
	if (res && res.AUTH_SEPCHAR) 
		useState().AUTH_SEPCHAR.value = res.AUTH_SEPCHAR
	if (res && res.UUIDONE) 
		useState().UUIDNONE.value = res.UUIDNONE
	if (res && res.TKNLIMIT) 
		useState().TKNLIMIT.value = res.TKNLIMIT
	if (res && res.REFRESHTIME) 
		useState().REFRESHTIME.value = res.REFRESHTIME
	if (res && res.ALLOW_REGISTER) 
		useState().ALLOW_REGISTER.value = res.ALLOW_REGISTER
	if (res && res.RESET_PASSWORD) 
		useState().RESET_PASSWORD.value = res.RESET_PASSWORD
	if (res && res.isDevelmode)
		useState().isDevelmode.value = res.isDevelmode
	if (res && res.htmlAttrs)
		useState().htmlAttrs.value = res.htmlAttrs
	if (res && res.dataSections) 
		useState().dataSections.value = res.dataSections
  if (res && res.cv_model)
    useState().cv_model.value = res.cv_model
}
export const get_urlpath = async (url: string, mode?: string): Promise<[any, string]> => {
	if (url.length == 0)
		return [{},'No URL defined']
	let text = ''
	let res: any = {}
	let error = null
	try {
		const response = await self.fetch(url, {
			method: 'GET',
		})
		if (url.includes('.json') || mode === 'json') {
			res = await response.json()
		} else {
			text = await response.text()
		}
		if (response.ok) {
			if (url.includes('.yaml') || mode === 'yaml') {
				res = YAML.parse(text)
			} else if (!url.includes('.json') && mode !== 'json') {
				res = text
			}
		} else {
			error = res.message
		}
	}
	catch (err: any) {
		error = err.message
	}
	return [res,error]
}
export const load_config = async (): Promise<[any, string]> => {
	const url = window.CONFIG_LOCATION ? window.CONFIG_LOCATION : '/config.yaml'
	// const url = window.CONFIG_LOCATION ? window.CONFIG_LOCATION : 'config.json'
  const [res,error] = await get_urlpath(url)
	if (error) {
		show_message(MessageType.Error, `'Config Load' -> ${error}`, 5000)
		useState().connection.value.state = 'connection.error'
		return [{},error]
	}
	return [res, error]
}
export const load_serv_config = async (): Promise<[any,string]> => {
	const url = useState().CONFURLS.value.srvconfig || ''
	if (url.length == 0)
		return [{},'No SRV URL defined']
  const [res,error] = await get_urlpath(url)
	if (error) {
		show_message(MessageType.Error, `'Serv Config Load' -> ${error}`, 5000)
		useState().connection.value.state = 'connection.error'
		return [{},error]
	}
	return [res,error]
}
export const get_serv_config = async (): Promise<[any,string]> => {
	const url = useState().CONFURLS.value.srvconfig || ''
	if (url.length == 0)
		return [{},'No SRV URL defined']
	const [res,errmsg] =	await fetch_json(url, 2000,true) 
	// fetch_json(url, 2000,to.meta.withauth,(res,errmsg) => {
	if (errmsg.length > 0) {
		return [{},errmsg]
	}
	return [res,errmsg]
}
export const load_vars_config = async (): Promise<[any,string]> => {
	const url = useState().CONFURLS.value.varsconfig || ''
	if (url.length == 0)
		return [{},'No URL defined']
	let text = ''
	let res: any = {}
	let error = null
	try {
		const response = await self.fetch(url, {
			method: 'GET',
		})
		if (url.includes('.json')) {
			res = await response.json()
		} else {
      text = await response.text()
		}
		if (response.ok) {
			if (url.includes('.yaml')) {
				res = YAML.parse(text)
			} else if (!url.includes('.json')) {
				res = text
			}
		} else {
			error = res.message
		}
	}
	catch (err: any) {
		error = err.message
	}
	if (error) {
		show_message(MessageType.Error, `'Vars Config Load' -> ${error}`, 5000)
		useState().connection.value.state = 'connection.error'
		return [{}, error]
	}
	return [res,error]
}
export const has_config = async(): Promise<boolean> => {
	let url = useState().CONFURLS.value.root || ''
	if (url.length === 0) {
		const [res,err] = await load_config()
		if (err && err.length > 0) {
			return false
		}
    set_config(res)
	  url = useState().CONFURLS.value.root || ''
	  if (url.length === 0) 
			return false
	}
	return true
}
export default {
	set_config,
	load_config,
  get_urlpath,
	load_serv_config,
	get_serv_config,
	load_vars_config,
	has_config,
}