<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" 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="true"
				:useLogin="true"
				:showinfo="show_info"
				:authinfo="auth_info"
				:needSave="needSave"
				:useEdit="true"
				:prefix="prefix"
				@onNavMenu="onNavMenu"
			/>
		  <div v-if="trackingList.length > 0" class="font-sans antialiased pb-3 border-b-1 border-gray-500 ">
				<h2 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_payload}"
				    :id="`${prefix}-sec_${prefix}_list`"
					>
						<span v-if="show_list" class="text-sm">{{t('tracking.list','List')}}</span>
						<button
							class="no-print text-sm float-right icon-btn mt-2 -mr-3 !outline-none text-gray-500 dark:text-gray-400"
							@click.prevent="onShowListBtn"
						>
							<div v-if="show_list" i-carbon-view-off />
							<div v-else class="noprint flex -mt-3">
								<div class="text-xs" :class="{'text-indigo-600 dark:text-indigo-300 mr-1': !show_payload}">{{t('tracking.list','List')}}</div>
								<div i-carbon-view />
							</div>
						</button>
				</h2>
				<ul v-if="show_list" class="flex mx-2 pb-2">
					<li v-for="(item,index) in trackingList" >
							<button 
								@click="onClickItemList(item,index)"
								class="btn-msg flex ml-2"
							>
							<div i-carbon-list /> <div class="ml-2 text-sm"> {{item}} </div> 
							</button> 
					</li>
				</ul>
			</div>
			<main
			  v-if="trackingData"
				:id="`${prefix}-sec_${prefix}_data`"
				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-60 sm:max-w-sm p-8 border-l-1  border-b-1 border-indigo-200 bg-gradient-to-b from-indigo-300 via-indigo-200 to-indigo-100 dark:bg-gray-600 dark:from-indigo-700 dark:via-indigo-600 dark:to-indigo-800"
				>
				  <div v-for="ky in dataFields">
						<label 
						  v-if="( ky === 'context' && showField.context ) || (ky !== 'payload' && ky !== 'context')"
						  :for="`filter-${ky}`"> 
						  <span class="text-xs text-gray-800 dark:text-gray-400">
							  {{t(`tracking.${ky}`,ky)}}  
							</span>
						</label>
						<input 
						  v-if="( ky === 'context' && showField.context ) || (ky !== 'payload' && ky !== 'context')"
							type="text"
							class="appearance-none bg-transparent w-full text-gray-900 dark:text-gray-200 py-2 leading-tight focus:outline-none"
							:class="{'border-b border-indigo-500': editsearch}"
							v-model="filterData[ky]"
							:disabled="!editsearch"
							:id="`filter-${ky}`"
						/>
					</div>
					<h2 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_payload}"
					>
						<span v-if="show_payload" class="text-sm">{{t('tracking.payload','payload')}}</span>
						<button
							class="no-print text-sm float-right icon-btn mt-2 -mr-3 !outline-none text-gray-500 dark:text-gray-400"
							@click.prevent="onPayloadBtn"
						>
							<div v-if="show_payload" i-carbon-view-off />
							<div v-else class="noprint flex -mt-3">
								<div class="text-xs" :class="{'text-indigo-600 dark:text-indigo-300 mr-1': !show_payload}">{{t('tracking.payload','payload')}}</div>
								<div i-carbon-view />
							</div>
						</button>
					</h2>
					<div v-if="show_payload && showField.payload" v-for="ky in payloadFields">
						<label :for="`filter-${ky}`"> 
						  <span class="text-xs text-gray-800 dark:text-gray-400">
							  {{t(`payload.${ky}`,ky)}}  
							</span>
						</label>
						<input 
							type="text"
							class="appearance-none bg-transparent w-full text-gray-900 dark:text-gray-200 py-2 leading-tight focus:outline-none"
							:class="{'border-b border-indigo-500': editsearch}"
							v-model="filterData.payload[ky]"
							:disabled="!editsearch"
							:id="`filter-${ky}`"
						/>
					</div>
					<div class="py-4 flex items-center gap-5 border-t-1 border-gray-500">
								<button
									v-if="editsearch"
									class="btn-msg flex-grow"
									@click="onSaveSearchBtn"
								>
									<span>{{ t('save', 'Save') }}</span>
								</button>
								<button v-else class="btn-msg flex-grow" @click="onResetSearchBtn">{{ t('reset', 'Reset') }}</button>
								<button v-if="!editsearch" class="btn-msg flex-grow" @click="onEditSearchBtn">{{ t('edit', 'Edit') }}</button>
								<button  v-else class="btn-msg flex-grow" @click="onCloseSearchBtn">{{ t('close', 'Close') }}</button>
					</div>
				</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-11/12 sm:w-full sm:max-w-sm shadow-xl bg-light-300 dark:bg-gray-900">
						<div class="relative float-right -top-2 right-2"> 
					   <span class=" text-gray-500 dark:text-gray-500 text-xs pr-1"> {{t('total','Total')}}: </span> 
					   <span class=" text-indigo-600 dark:text-indigo-400 text-sm pr-1"> {{trackingDataFilter.length}} </span> 
					   <span class=" text-gray-500 dark:text-gray-500 text-xs pr-1"> {{t('of','of')}} </span> 
					   <span class=" text-gray-600 dark:text-gray-400 text-sm pr-1"> {{trackingData.length}} </span> 
						</div> 
						<div class="flex flex-col container max-w-fit mt-5 mx-auto w-full lg:items-center lg:justify-center bg-white dark:bg-gray-800 rounded-lg shadow">
							<ul class="flex flex-col divide-y divide-gray-500 w-full">
							 <li class="flex flex-row py-2 lg:py-0 text-sm lg:text-base">
									<div class="flex-row select-none flex lg:flex-1 lg:items-center">
										<div class="flex flex-row w-15 lg:h-10 lg:justify-center lg:items-center text-gray-600 dark:text-gray-400 ml-2 lg:ml-3 cursor-pointer font-normal lg:text-sm" :class="{'m-0': orderBy === 'what'}">
											 <div v-if="orderBy === 'what' && sortMode !== 'descending'" @click="onToggelSort" class="text-indigo-600 dark:text-indigo-400" i-carbon-arrow-up /> 
										   <div @click="onField('what')" :class="{'border-b border-indigo-500': orderBy === 'what'}">{{t('tracking.what','what')}} </div>
											 <div v-if="orderBy === 'what' && sortMode === 'descending'" @click="onToggelSort" class="text-indigo-600 dark:text-indigo-400" i-carbon-arrow-down/>
										</div>
										<div class="flex flex-row w-15 lg:w-30 sm:max-w-sm lg:h-10 lg:justify-center lg:items-center ml-2 text-gray-600 dark:text-gray-400 lg:text-xs cursor-pointer" :class="{'m-0': orderBy === 'data'}">
											<div v-if="orderBy === 'data' && sortMode !== 'descending'" @click="onToggelSort" class="text-indigo-600 dark:text-indigo-400" i-carbon-arrow-up /> 
										  <div @click="onField('data')" :class="{'border-b border-indigo-500': orderBy === 'data'}">{{t('tracking.data','data')}} </div>
											<div v-if="orderBy === 'data' && sortMode === 'descending'" @click="onToggelSort" class="text-indigo-600 dark:text-indigo-400" i-carbon-arrow-down/>
										</div>
										<div class="flex-1 pl-1">
											<div class="flex flex-row">
												<div class="flex flex-row w-20 text-gray-600 dark:text-gray-400 cursor-pointer font-normal lg:text-sm">
													<div v-if="orderBy === 'where' && sortMode !== 'descending'" @click="onToggelSort" class="text-indigo-600 dark:text-indigo-400 mt-1" i-carbon-arrow-up /> 
													<div @click="onField('where')" :class="{'border-b border-indigo-500': orderBy === 'where'}">{{t('tracking.where','where')}} </div>
													<div v-if="orderBy === 'where' && sortMode === 'descending'" @click="onToggelSort" class="text-indigo-600 dark:text-indigo-400 mt-1" i-carbon-arrow-down/>
												</div>
												<button
													class="no-print text-sm icon-btn mt-2 mr-3 !outline-none text-gray-500 dark:text-gray-400"
													@click.prevent="onToggleView('context')"
												>
													<div v-if="showField.context" class="flex -mt-1" >
														<div class="hidden lg:block ml-5 mr-2 mt-0.8 text-gray-500 dark:text-gray-500 text-[0.8em]"> {{t('tracking.context','context')}} </div>
														<div class="lg:hidden ml-5 mt-1 text-gray-500 dark:text-gray-500 text-[0.8em]"> {{t('tracking.ctx','ctx')}} </div>
													  <div i-carbon-view-off />
													</div>
												  <div v-else class="noprint flex -mt-1">
														<div class="mr-2 text-xs" :class="{'line-through text-indigo-600 dark:text-indigo-300': !showField.context}">{{t('tracking.context','context')}}</div>
													  <div i-carbon-view />
												  </div>
												</button>
											</div>
										</div>
										<div class="flex-1 pl-1 mr-5 ">
											<button
												class="no-print text-sm icon-btn mt-2 -mr-3 !outline-none text-gray-500 dark:text-gray-400"
												@click.prevent="onToggleView('payload')"
											>
												<div v-if="showField.payload" class="flex -mt-1">
											     <div class="font-normal text-gray-600 dark:text-gray-400 lg:text-sm mr-1 -mt-0.8">{{t('tracking.auth','auth')}}</div>
													  <div i-carbon-view-off />
												</div>
												<div v-else class="noprint flex -mt-3">
											    <div class="font-normal text-gray-600 dark:text-gray-400 lg:text-sm" :class="{'line-through text-indigo-600 dark:text-indigo-300 mr-1': !showField.payload}">{{t('tracking.auth','auth')}}</div>
													<div i-carbon-view />
												</div>
											</button>
										</div>
										<div class="flex flex-row lg:justify-center lg:mr-10 cursor-pointer font-normal lg:text-sm">
											<div v-if="orderBy === 'when' && sortMode !== 'descending'" @click="onToggelSort" class="text-indigo-600 dark:text-indigo-400 mt-1" i-carbon-arrow-up /> 
										  <div @click="onField('when')" class="text-gray-600 dark:text-gray-400" :class="{'border-b border-indigo-500': orderBy === 'when'}">
											   {{t('tracking.when','when')}}
											</div>
											<div v-if="orderBy === 'when' && sortMode === 'descending'" @click="onToggelSort" class="text-indigo-600 dark:text-indigo-400 mt-1" i-carbon-arrow-down/>
										</div>
									</div>
								</li> 
								<li v-for="(item,index) in trackingDataFilter" class="flex flex-col lg:flex-row">
									<div v-if="item.when" class="flex-col select-none cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-900 flex lg:flex-row lg:flex-1 lg:items-center p-4">
										<div class="flex flex-row lg:flex-col lg:w-15 sm:max-w-xs lg:h-10 lg:justify-center lg:items-center pb-2 lg:pb-0 pl-1 text-gray-900 dark:text-gray-100 font-normal text-sm">
									    <div class="lg:hidden text-sm w-20 text-gray-600 dark:text-gray-400 mt-0.8"> {{t('tracking.what','what')}}: </div>
										  <div class="flex-grow-0">{{item.what}}</div> 
										</div>
										<div class="flex flex-row lg:flex-col lg:w-30 sm:max-w-sm lg:h-10 lg:justify-center lg:items-center pl-1">
									    <div class="lg:hidden text-xs w-20 text-gray-600 dark:text-gray-400 mt-0.8"> {{t('tracking.data','data')}}: </div>
										  <div class=" text-gray-900 dark:text-gray-100 text-xs"> {{item.data}} </div>
										</div>
										<div class="flex flex-row lg:flex-1 pl-1">
								      <div class="lg:hidden text-sm w-20 text-gray-600 dark:text-gray-400 mt-0.8"> {{t('tracking.where','where')}}: </div>
										  <div class="flex-1 flex-col">
  											<div class="font-normal text-sm text-gray-600 dark:text-gray-400">{{item.where}}</div>
												<div v-if="showField.context" v-for="(line,pos) in item.context.split(')')" :key="pos" class="text-gray-500 dark:text-gray-500 text-[0.8em] mt-2">
												{{`${line})`}}
												</div>
											</div>
										</div>
										<div v-if="showField.payload" class="flex-1 pl-1 pb-2 lg:pb-0">
								      <div class="lg:hidden text-xs w-20 text-gray-600 dark:text-gray-400 mt-0.8"> {{t('tracking.auth','auth')}}: </div>
											<table v-if="item.payload" class="table-auto lg:mt-2">
											  <tbody>
												<tr v-for="key,idx in payloadFields" :key="idx" class="text-gray-500 dark:text-gray-500 text-[0.8em] mt-2">
														<td v-if="item.payload[key]" class="text-xs text-gray-500 dark:text-gray-400">{{t(`payload.${key}`,key)}}</td> 
														<td v-if="item.payload[key]" class="pl-5 text-gray-600 dark:text-gray-300">{{`${auth_get_value(key,item.payload)}`}}</td>
												</tr>
												</tbody>
											</table>
										</div>
										<div class="flex flex-row lg:justify-center">
									    <div class="lg:hidden pl-1 text-xs w-20 text-gray-600 dark:text-gray-400 mt-0.8"> {{t('tracking.when','when')}}: </div>
											<div class="pl-1 text-gray-600 dark:text-gray-200 text-xs">{{`${format_date(parseInt(item.when))}`}}</div>
											<button v-if="edititems" 
											  @click="onClickItem(item,index)"
												class="absolute right-15 lg:relative lg:right-0  w-10 text-right flex justify-end"
											>
												<svg width="20" fill="currentColor" height="20" class="hover:text-gray-800 dark:hover:text-white dark:text-gray-200 text-gray-500" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg">
													<path d="M1363 877l-742 742q-19 19-45 19t-45-19l-166-166q-19-19-19-45t19-45l531-531-531-531q-19-19-19-45t19-45l166-166q19-19 45-19t45 19l742 742q19 19 19 45t-19 45z"></path>
												</svg>
											</button>
										</div>
									</div>
								</li>
							</ul>
						</div>
					</div>
				</div>
			</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 { isDark} from '~/composables'
import useState from '~/hooks/useState'
import { parseJwt,checkUserAuth } from '~/hooks/utilsAuth'
import { load_data_model,load_currentRoute} from '~/hooks/loads'
import { fetch_json } from '~/hooks/utils'
import { track_action } from '~/hooks/tracking'
import { AuthPayloadType,TrackActionShowType, MessageType, TrackActionType} from '~/typs'
import { MessageBoxType, NavPosition, InputBtnsType, ShowInfoType, ModelType} from '~/typs/cv'
import { show_message,send_data} from '~/hooks/utils'
import { format_date} from '~/hooks/tools'

const trackingList = ref([] as string[])
const trackingData = ref([] as TrackActionType[])
const filterData = ref({} as TrackActionType)
const dataFields = ref(['what','data','where','context','payload','when'])
const payloadFields = ref(['id','exp','uuid','data','orig_iat'])
const showField = ref({what: true,data: true,where: true,context: true,payload: true,when: true} as TrackActionShowType)
const show_payload = ref(false)
const orderBy = ref('')
const sortMode = ref('')
const show_list = ref(true)

const filterPayload = (item: AuthPayloadType):boolean => {
	let include = true
	for (const key in item) {
    if (!include)
		  break
		const keyval = filterData.value.payload && filterData.value.payload[key] ? filterData.value.payload[key] : ''
		if (keyval.length == 0)
		  continue
		let val = ''
		switch(key) {
			case 'orig_iat':
			case 'exp':
				val = typeof item[key] === 'string' ? format_date(parseInt(item[key] as string)*1000) : format_date((item[key] as number)*1000)
				break
			default:
				val = item[key]
		}
		if (val.length > 0 && !val.includes(keyval)) {
			include = false      
		}
	}
	return include
}
const filterItem = (item: TrackActionType, index: number):boolean => {
	let include = true
	for (const key in item) {
    if (!include)
		  break
		if (key !== 'payload' && filterData.value[key].length == 0)
		  continue
		let val = ''
		switch(key) {
			case 'auth':
				break
			case 'payload':
				include = filterPayload(item.payload as AuthPayloadType)
			  // const auth = parseJwt(item.auth)	
				break
			case 'when':
				val = format_date(parseInt(item.when as string))
				if (!val.includes(filterData.value[key] as string)) {
					include = false      
				}
				break
			default:
				val = item[key]
		}
		if (val.length > 0 && !val.includes(filterData.value[key])) {
			include = false      
		}
	}
	return include
}
const trackingDataFilter = computed(() => {
	if (orderBy.value.length > 0)  {
		if (sortMode.value === 'descending') 
   	  return trackingData.value.filter(filterItem).sort((a,b) => a[orderBy.value].localeCompare(b[orderBy.value])).reverse()
		else 
   	  return trackingData.value.filter(filterItem).sort((a,b) => a[orderBy.value].localeCompare(b[orderBy.value]))
	} else {
   	return trackingData.value.filter(filterItem)
  }
})
const prefix = 'tracking'
const edititems = ref(false)
const editsearch = 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 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 onShowListBtn = () => {
	show_list.value = !show_list.value 
}
const resetFilter = () => {
	filterData.value = {
    when: '',
    what: '',
    where: '',
    context: '',
		data: '',
    auth: '',
		payload: {
			id: '',
			data: '',
			uuid: '',
			exp: '',
			orig_iat: '',
		},
		idx: -1,
	}
}
const refresh = () => {
	show_content.value = false
	setTimeout(() => show_content.value = true, 1)
}
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 onSaveSearchBtn = () => {
	 // TODO save search
}
const onCloseSearchBtn = () => {
	editsearch.value = false
}
const onResetSearchBtn = () => {
	editsearch.value = true
	resetFilter()
}
const onEditSearchBtn = () => {
	editsearch.value = true
}
const onPayloadBtn = () => {
	show_payload.value = !show_payload.value
	if (show_payload.value) {
		showField.value.payload = 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',
	} 
	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 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
			})
		})
  }
}
const onField = (field: string) => {
	orderBy.value = orderBy.value === field ? '': field
}
const onToggleView = (field: string) => {
  showField.value[field] = !showField.value[field] 
}
const onToggelSort = () => {
	sortMode.value = sortMode.value === '' ? 'descending' : ''
}
const onClickItem = (item: TrackActionType, pos: number) => {
	// if (item && item.auth && item.auth.length > 0) {
	//   const payload = parseJwt(item.auth)
	// }
}
const auth_get_value = (ky: string, itm: AuthPayloadType):string => {
  let value = ''
  switch(ky) {
		case 'exp':
		case 'orig_iat':
      value = format_date(parseInt(`${itm[ky]}`)*1000)
			break
		default:
			value=itm[ky] ? itm[ky] : ''
	}
	return value
}
const get_tracking_data = async (target: string): Promise<[any,string]> => {
	const url = useState().CONFURLS.value.tracking || ''
	if (url.length == 0)
		return [{},'No SRV URL defined']
	const urlpath = `${url}/${target}`
	const [res,errmsg] =	await fetch_json(urlpath, 2000,true) 
	if (errmsg.length > 0) {
		return [{},errmsg]
	}
	return [res,errmsg]
}
const load_tracking_data = async (target: string): Promise<[any,string]> => { 
  const [res,errmsg] =	await get_tracking_data(target)
	if (errmsg && errmsg.length > 0) {
		show_content.value = false
	} else {
		trackingData.value = res.map((itm: TrackActionType,idx: number) => {
      itm.payload = parseJwt(itm.auth)
			itm.idx = idx
			return itm
		})
	}
  resetFilter()
	return [res,errmsg]
//	track_action(null, { ref: 'tracking',text: 'tracking data'}, 'load')
}
const onClickItemList = async (item: string, index: Number) => {
  await load_tracking_data(item)	
}
onBeforeMount(async() => {
  useState().dataSections.value = [`sec_${prefix}_list`,`sec_${prefix}_data`]
	const url = useState().CONFURLS.value.trackinglist || ''
	if (url.length == 0)
		return [{},'No SRV URL defined']
	const [res,errmsg] =	await fetch_json(url, 2000,true) 
	if (errmsg.length > 0) {
		show_content.value = false
	} else {
		show_list.value = true
		show_content.value = true
		trackingList.value = res		
	}
})
</script>