import sharedService from './../services/shared.service';

import { createRouter, createWebHashHistory } from '@ionic/vue-router';
import { NavigationGuardNext, RouteLocationNormalized, RouteRecordRaw } from 'vue-router';

const routes: Array<RouteRecordRaw> = [
	{
		path: '',
		redirect: '/home',
	},
	{
		path: '/home',
		name: 'Home',
		component: () => import('../views/common/HomePage.vue'),
	},
	{
		path: '/login',
		name: 'Login',
		component: () => import('../views/common/LoginPage.vue'),
	},
	{
		path: '/as',
		redirect: '/as/defting',
	},
	{
		path: '/as/defting',
		component: () => import('../views/as/AsDeftIngPage.vue'),
	},
	{
		path: '/as/defting/:id',
		component: () => import('../views/as/AsDeftIngViewPage.vue'),
	},
	{
		path: '/as/deftdone',
		component: () => import('../views/as/AsDeftDonePage.vue'),
	},
	{
		path: '/as/deftdone/:id',
		component: () => import('../views/as/AsDeftDoneViewPage.vue'),
	},
	{
		path: '/po',
		redirect: '/po/deftmang',
	},
	{
		path: '/po/deftmang',
		component: () => import('../views/po/PoDeftMangPage.vue'),
	},
	{
		path: '/po/deftmang/:id',
		component: () => import('../views/po/PoDeftMangViewPage.vue'),
	},
	{
		path: '/po/deftque',
		component: () => import('../views/po/PoDeftQuePage.vue'),
	},
	{
		path: '/po/deftque/:id',
		component: () => import('../views/po/PoDeftQueViewPage.vue'),
	},
	{
		path: '/po/roomrev',
		component: () => import('../views/po/PoRoomRevPage.vue'),
	},
	{
		path: '/po/roomapp',
		component: () => import('../views/po/PoRoomAppPage.vue'),
	},
	{
		path: '/address',
		component: () => import('../views/common/SiteAddressPage.vue'),
	},
	{
		path: '/pushdev',
		component: () => import('../views/common/PushDevPage.vue'),
	},
	{
		path: '/sample',
		component: () => import('../views/common/SamplePage.vue'),
	},
	{
		path: '/test',
		component: () => import('../views/common/SamplePage.vue'),
	},
	{
		path: '/error',
		component: () => import('../views/common/ErrorPage.vue'),
	},
	{
		path: '/:pathMatch(.*)*',
		redirect: '/home',
	},
];

const router = createRouter({
	history: createWebHashHistory(process.env.BASE_URL),
	routes,
});

router.beforeEach(async (to: RouteLocationNormalized, _: RouteLocationNormalized, next: NavigationGuardNext) => {
	if (!to.path.startsWith('/login') && !['/error', '/test', '/sample'].includes(to.path)) {
		const path = await sharedService.isLogined(to.path);
		switch (path) {
			case '/login':
				next({ path: '/login', name: 'Login', query: { next: to.path } });
				break;
			default:
				if (!to.path.startsWith(path)) {
					next({ path: path });
				} else {
					next();
				}
				break;
		}
	} else {
		next();
	}
});
export default router;
