<template>
	<div
		v-if="openMessageBox"
		class="fixed inset-0 bg-gray-600 overflow-y-auto h-full w-full z-80 dark:bg-gray-900 opacity-97"
	>
	<message-box-view
		:messageType="message_type"
		:openMessageBox="openMessageBox"
		:show_input="show_input"
		:input_placeholder="input_placeholder"
		:input_btns="input_btns"
		:select_ops="select_ops"
		:data_url_encoded="data_url_encoded"
		:inpType="oneInputType"
		@onInput="onInput"
		@onMessageBox="onMessageBox"
		@onLoadModel="onLoadModel"
	/>
	</div>
	<div v-if="show_content && servConfig" class="font-sans antialiased">
		<div class="container mx-auto max-w-screen-2xl main-container">
			<nav-menu
			  class="bg-light-300 dark:bg-gray-900"
				:position="NavPosition.header"
				:openMessageBox="openMessageBox"
				:fixMenu="fixMenu"
				:show_infopanel="show_infopanel"
				:dataAuth="false"
				:useInfoPanel="false"
				:useLogin="true"
				:showinfo="show_info"
				:authinfo="auth_info"
				:needSave="needSave"
				:useEdit="true"
				:prefix="prefix"
				@onNavMenu="onNavMenu"
			/>
			<main
				:id="`${prefix}-wrapper`"
				class="rounded flex flex-col sm:flex-row-reverse shadow-2xl"
				:class="{ 'mt-11': fixMenu }"
			>
				<div
					v-if="show_infopanel"
					id="sidebar"
					class="rounded-r w-full lg:w-80 sm:max-w-sm p-8 border-l-1 border-indigo-200 bg-gradient-to-b from-indigo-300 via-indigo-200 to-indigo-100 dark:bg-gray-600 dark:from-indigo-500 dark:via-indigo-400 dark:to-indigo-800"
				>
				</div>
				<div class="content w-full p-5">
					<div class="prose flex-1 p-4 border-1 rounded-md border-gray-300 dark:border-gray-600 lg:w-4/12 sm:w-full sm:max-w-sm shadow-xl bg-light-300 dark:bg-gray-900">
							<div v-for="(sec,idxsec) in data_sections" :key="idxsec"
							:id="`${prefix}-${sec}`"
							class="prose mb-2"
							:class="{ 'page-break': idxsec > 0 }"
					  	>
								<h2 v-if="show_sections[sec]" class="section-headline my-4  px-5 pb-2" 
									:class="{'bg-gray-200 dark:bg-gray-700 border-1 rounded-tl-xl rounded-r-3xl border-indigo-500': show_sections[sec].enabled && show_sections[sec].view}"
								>
									<span v-if="show_sections[sec].enabled && show_sections[sec].view" class="text-base">{{t(`vars.${sec}`,sec)}}</span>
									<button
										class="no-print text-sm float-right icon-btn mt-3 !outline-none text-gray-500 dark:text-gray-400"
										@click.prevent="onSection(sec)"
									>
										<div v-if="show_sections[sec].view && show_sections[sec].enabled" i-carbon-view-off />
										<div v-else class="noprint flex -mt-4">
											<div class="mr-2 text-xs" :class="{'line-through text-indigo-600 dark:text-indigo-300': !show_sections[sec].enabled}">{{t(`vars.${sec}`,sec)}}</div>
											<div i-carbon-view />
										</div>
									</button>
									<button
									  v-if="show_sections[sec].view && show_sections[sec].enabled"
										class="no-print text-sm float-right icon-btn mt-3 mr-1 !outline-none text-gray-500 dark:text-gray-400"
										@click="onHelp(sec)" 
									>
										<div i-carbon-help/>
									</button>
									<button
									  v-if="show_sections[sec].view && show_sections[sec].enabled"
										class="no-print text-sm float-right icon-btn mt-3 mr-2 !outline-none text-gray-500 dark:text-gray-400"
										@click.prevent="onHome()"
									>
										<div i-carbon-home />
								  </button>
								</h2>
								<div v-if="show_sections[sec] && show_sections[sec].enabled && show_sections[sec].view && show_sections[sec].help"
								 	 class="helpbox" v-html="t(`info.${sec.replace('sec_','')}`,'')"
								/>
								<div v-if="show_sections[sec] && show_sections[sec].enabled && show_sections[sec].view"
								     v-for="(itm,idxitm) in Object.keys(varsConfig[sec])"
									   :key="idxitm"
								>
									<div 
									 v-if="servConfig[itm]"
									 class="flex flex-col items-start py-2" 
									 :class="{'border-b border-indigo-500': edititems && show_items[`${sec}.${itm}`].enabled && simpleInputype(varsConfig[sec][itm].typ)}"
									>
										<h4 class="sectionitem w-full" :class="{'-mt-2 -mb-7': varsConfig[sec][itm].typ === 'Bool'}">
											<span v-if="varsConfig[sec][itm].typ !== 'Bool'" 
												class="text-base"
											  :class="{'text-gray-300 dark:text-gray-600': !show_items[`${sec}.${itm}`].enabled}"
											>
												{{t(`${sec}.${itm}`,itm)}}
											</span>
											<button
												v-if="!auth_info.viewchange"
												class="no-print text-sm float-right icon-btn mt-1 !outline-none text-gray-500 dark:text-gray-400"
												@click.prevent="onHelp(sec,itm)"
											>
												<div class="noprint flex">
													<div i-carbon-help />
												</div>
											</button>
										</h4>
										<div v-if="show_items[`${sec}.${itm}`].help" class="helpbox" v-html="t(`info${sec}.${itm}`,'')"/>
										<DataInput
										  v-if="varsConfig[sec][itm].typ === InputValueOption.object"
										  :dataVars="varsConfig[sec][itm].vars"
											:section="sec"
										  :typ="varsConfig[sec][itm].typ"
											:dataValue="servConfig[itm]"
											:varname="itm"
											:title="`${sec}.${itm}`"
										  :labelitms="varsConfig[sec][itm].labelitms? varsConfig[sec][itm].labelitms : ''"
											:edititem="edititems"
											:showitem="show_items[`${sec}.${itm}`].enabled"
										  :validate="varsConfig[sec][itm].valid ? varsConfig[sec][itm].valid : ''"
				              :messages="true"
											@input-change="onInputChange"
										/>	
									  <InputValue 
										  v-if="varsConfig[sec][itm].typ !== InputValueOption.object"
											:section="sec"
										  :typ="varsConfig[sec][itm].typ"
											:vardef="varsConfig[sec][itm]"
											:dataValue="servConfig[itm]"
											:varname="itm"
											:title="`${sec}.${itm}`"
										  :labelitms="varsConfig[sec][itm].labelitms? varsConfig[sec][itm].labelitms : ''"
											:edititem="edititems"
											:showitem="show_items[`${sec}.${itm}`].enabled"
										  :validate="varsConfig[sec][itm].valid ? varsConfig[sec][itm].valid : ''"
				              :messages="true"
											@input-change="onInputChange"
										/>	
									</div>
								</div>
							</div>
							<div class="py-4 flex items-center gap-5 border-t-1 border-gray-500">
								<button
									v-if="edititems"
									class="btn-msg flex-grow"
									@click="onSaveBtn"
								>
									<span>{{ t('save', 'Save') }}</span>
								</button>
								<button v-if="!edititems" class="btn-msg flex-grow" @click="onEditBtn">{{ t('edit', 'Edit') }}</button>
								<button  v-else class="btn-msg flex-grow" @click="onCloseBtn">{{ t('close', 'Close') }}</button>
							</div>
					</div>
				</div>
				<hr class="hr-sep" />
			</main>
			<div
   	    v-if="show_content" 
				class="mr-auto w-full lg:w-1/2 text-center text-sm mx-2 text-gray-600 border-gray-300 border-1 border-b-0 rounded-t-xl"
			>
				<nav-menu
				  class="shadow-xl bg-light-300 dark:bg-gray-900"
					:position="NavPosition.footer"
					:fixMenu="fixMenu"
					:show_infopanel="show_infopanel"
				  :dataAuth="false"
				  :useInfoPanel="false"
				  :useLogin="true"
					:showinfo="show_info"
					:authinfo="auth_info"
					:needSave="needSave"
				  :useEdit="true"
					prefix="sec"
				  :openMessageBox="openMessageBox"
					@onNavMenu="onNavMenu"
				/>
			</div>
		</div>
	</div>
<div v-else class="text-center m-auto">
	<img v-if="isDark"
		class="m-auto mt-5"
		width="250"
		:src="`${assetsPath}/images/genadmin_b.svg`"
	/>
	<img v-else
		class="m-auto mt-5"
		width="250"
		:src="`${assetsPath}/images/genadmin_w.svg`"
	/>
	<h2 class="mt-8 text-2xl text-gray-700 dark:text-gray-400">{{ t('message.loading', 'Loading') }}...</h2>
	<h4>{{useState().connection.value.state}}</h4>
</div>
</template>
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
const i18n = useI18n()
const { t } = useI18n()
const router = useRouter()

import MessageBoxView from '~/components/MessageBoxView.vue'
import NavMenu from '@/NavMenu.vue'
import DataInput from '@/forms/DataInput.vue'
import InputValue from '@/InputValue.vue'
import { isDark } from '~/composables'
import useState from '~/hooks/useState'
import { parseJwt,checkUserAuth } from '~/hooks/utilsAuth'
import { load_data_model,load_currentRoute } from '~/hooks/loads'
import { track_action } from '~/hooks/tracking'
import { load_vars_config,get_serv_config} from '~/hooks/config'
import { MessageType} from '~/typs'
import { MessageBoxType, NavPosition, InputBtnsType, ShowInfoType, ModelType} from '~/typs/cv'
import { InputValueOption,SecViewType} from '~/typs/inputs'
import { ServConfigType} from '~/typs/config'
import { show_message,send_data} from '~/hooks/utils'

const prefix = 'cfg'
const varsConfig = useState().varsConfig
const servConfig = ref({} as ServConfigType)

const show_sections = ref({} as SecViewType)
const show_items = ref({} as SecViewType)
const edititems = ref(false)

const assetsPath = useState().ASSETS_PATH
const routeKy = router.currentRoute.value.params.ky || router.currentRoute.value.query.k || ''
const message_type = ref(MessageBoxType.NotSet)
const fixMenu = ref(false)
const show_content = ref(true)
const show_infopanel = ref(false)
const openMessageBox = ref(false)
const needSave = ref(false)
const show_input = ref(false)
const data_url_encoded = ref('')
const input_btns = ref([] as InputBtnsType[])
const input_placeholder = ref('')
const oneInputType = ref('')

const onSection = (sec: string) => {
	if (!show_sections.value[sec].enabled) {
	  show_sections.value[sec].view = true
	  show_sections.value[sec].enabled = true
		return
	} else {
	  show_sections.value[sec].view = !show_sections.value[sec].view
	}
}
const onHelp = (sec: string, itm?: string) => {
	if (itm)
	  show_items.value[`${sec}.${itm}`].help = !show_items.value[`${sec}.${itm}`].help
	else
	  show_sections.value[sec].help = !show_sections.value[sec].help
}
const onInputChange = (data: {sec: string, key: string, idx:number,  val: any}) => {
	if (data.key && typeof servConfig.value[data.key] !== 'undefined') {
  	servConfig.value[data.key] = data.val
		if (data.sec) 
			check_item_section(data.sec,data.key)
	}
}
const simpleInputype = (typ: string): boolean => {
	switch(typ) {
		case 'String':
		case 'Number':
		case 'Array:String':
		 return true
		default:
		 return false
	}
}
const check_item_section = (sec: string, itm: string) => {
	// show_items.value[`${sec}.${itm}`].enabled = servConfig.value[itm]
	switch(itm) {
		case 'useJWT':
		case 'useRepo':
	    show_sections.value[sec].enabled = servConfig.value[itm]
			break
		case 'useAuthz':
	    show_items.value[`${sec}.authzModel`].enabled = servConfig.value[itm]
	    show_items.value[`${sec}.authzPolicy`].enabled = servConfig.value[itm]
			break
	}
}
const onInput = (btn: InputBtnsType) => {
	switch (btn.id) {
		case 'ok':
			break
		case 'cancel':
			break
	}
	show_input.value = false
}
const select_ops = ref({} as ModelType)
const show_info = ref({} as ShowInfoType)
const auth_info = useState().authinfo
const useEdit = ref(true)

const data_sections = useState().dataSections 

const refresh = () => {
	show_content.value = false
	setTimeout(() => show_content.value = true, 1)
}
const onSaveBtn = () => {
	// edititems.value = false
	// needSave.value = false
	onNavMenu({ src: 'save', target: '' })
}
const onCloseBtn = () => {
	edititems.value = false
	needSave.value = false
}
const onEditBtn = () => {
	edititems.value = true
	needSave.value = true
	auth_info.value.editable = true
	useEdit.value = true
}

const onNavMenu = (item: { src: string, target: string }) => {
	switch (item.src) {
		case 'editable':
			if (edititems.value) {
			  onCloseBtn()
			} else {
			  onEditBtn()
			}
			break
		case 'locale':
	    track_action(null, { ref: 'locale',text: i18n.locale.value}, 'locale')
			refresh()
			break
		case 'infopanel':
	    track_action(null, { ref: 'onNavMenu',text: 'item.src'})
			show_infopanel.value = !show_infopanel.value
			break
		case 'fixmenu':
	    track_action(null, { ref: 'onNavMenu',text: 'item.src'})
			fixMenu.value = !fixMenu.value
			break
		case 'endinput':
			show_input.value = false
			break
		case 'select':
	    track_action(null, { ref: 'onNavMenu',text: 'item.src'})
			message_type.value = MessageBoxType.Select
			openMessageBox.value = true
			break
		case 'save':
	    track_action(null, { ref: 'onNavMenu',text: 'item.src'})
			input_placeholder.value = `${t('name', 'Name')} o 'config'`
			show_input.value = true
			message_type.value = MessageBoxType.Save
			data_url_encoded.value = ''
			openMessageBox.value = true
			break
		case 'editable':
	    track_action(null, { ref: 'onNavMenu',text: 'item.src'})
			useState().authinfo.value.editable = !useState().authinfo.value.editable
			const state = useState().authinfo.value.editable ? 'on' : 'off'
			const msgTyp = state === 'on' ? MessageType.Warning :  MessageType.Info
      show_message(msgTyp, `${t('saveload.editMode','Edit Mode')} ${t('cv.'+state,'')}`)
			break
		case 'viewchange':
	    track_action(null, { ref: 'onNavMenu',text: 'item.src'})
			useState().authinfo.value.viewchange = !useState().authinfo.value.viewchange
			break
		case 'goto':
			if (item.target) {
				const dom_id = document.getElementById(item.target)
				if (dom_id) {
					track_action(null, { ref: 'gotp',text: item.target}, 'goto')
					dom_id.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' })
					setTimeout(() => window.scrollBy(0, -40), 4000)
				}
			}
			break
	}
}
const saveData = async(mode: string,val: string) => {
	const url = useState().CONFURLS.value.sendsrvconfig || ''
  message_type.value = MessageBoxType.Save
	const payload = parseJwt(localStorage.getItem(useState().AUTHKEY.value))
	const data: any = {
		id:  payload.id ? payload.id : '',
		val: val.length > 0 ? val : 'config',
		config: servConfig.value,
	} 
	if (mode == 'send' && url.length > 0) {
		onMessageBox({src: 'done', val: ''})
		const [res,err] = await send_data(url, data, true, true)
		if (err && err.length > 0 ) {
			show_message(MessageType.Error, `Error: ${err}`,2000)
		} else if (res && res.status && res.status === 'ok') {
	    track_action(null, { ref: 'saveData',text: `${url} -> ${val}`})
		  show_message(MessageType.Success, `${t('saveload.dataSaved','Data saved')}`,2000,() => { 
				edititems.value = false
				needSave.value = false
		  })
		}
	} else {
	  track_action(null, { ref: 'saveData',text: `local_json -> ${val}`})
		show_message(MessageType.Warning, `${t('saveload.saveLocalFile','Save Data to Local File')}`,2000,() => { 
		  data_url_encoded.value = `text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(data))}`
		})
	}
}
const onMessageBox = (item: { src: string, val: string }) => {
	switch (item.src) {
		case 'savedata':
			show_input.value = false
			saveData('local', item.val)
			break
		case 'sendata':
			show_input.value = false
			saveData('send', item.val)
			break
		case 'oneinput':
			const r = async() => {
				if (await checkUserAuth(item.val)) {
					oneInputType.value='text'
			    openMessageBox.value = false
				  if (!await load_currentRoute(router.currentRoute.value)) {
					   show_message(MessageType.Error, `${t('saveload.loaderror','Load error')}`,2000)
					}
				} else {
					show_message(MessageType.Error, `${t('saveload.autherror','Auth error')}`,2000)
				}
			}
			r()
		  break
		case 'endinput':
			show_input.value = false
			break
		case 'done':
			openMessageBox.value = false
			break
		case 'open':
			openMessageBox.value = true
			break
	}
}
const onHome = () => {
	const dom_body = document.getElementsByTagName('body')[0]
	if (dom_body) {
		dom_body.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' })
	}
}
const onLoadModel = (model: { id: string}) => {
	const url = useState().CONFURLS.value.data || ''
	if ( url.length > 0) {
		return
	}
	if (useState().selectOps.value[model.id]) {
		load_data_model(model.id, url, routeKy as string,true,() => {
	    show_content.value = false
		  show_message(MessageType.Success, `${t('saveload.dataLoaded','Data loaded')}`,2000,() => { 
	      show_content.value = true
			})
		})
  }
}
onBeforeMount(async() => {
	if (Object.keys(useState().varsConfig.value).length === 0) {
    const [res, err]  = await load_vars_config()
	  if (err && err.length > 0) {
		  show_content.value = false
		} else {
      useState().varsConfig.value = res
		}
	} 
	useState().dataSections.value = Object.keys(useState().varsConfig.value)
	useState().dataSections.value.forEach(sec => {
		show_sections.value[sec] = { view: true, enabled: true, help: false}
	  Object.keys(useState().varsConfig.value[sec]).forEach(itm => {
		  show_items.value[`${sec}.${itm}`] = { view: true, enabled: true, help: false}
		})
	})
	useState().current_modelid.value = ''
	const [res,errmsg] =	await get_serv_config()
	if (errmsg && errmsg.length > 0) {
		show_content.value = false
	} else {
     servConfig.value = res
	}
	track_action(null, { ref: 'config',text: 'server config'}, 'mount')
})
</script>