import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import PageView from '@/views/PageView.vue'
import { usePageStore } from '@/stores/pages'
import axios from 'axios'

let locale:String = (localStorage.getItem('lang') || 'de')
let pages = [] as Array<any>
let addPages = [] as Array<any>


export async function loadDynamicPages(newLocale:String){
  locale = newLocale
  const response = await axios.get('https://strapi.kornblum.one/api/pages?locale='+locale, {
    headers: {
      Authorization: "Bearer 28f1084766b4010f8a295faf9fdbf83bc35b48fd0c678c09468e503a1ac474b49b03c5c8d2fbb98e1876427ace5f9d58180e3c79afa6d172c97738056e28c7adecff2bb9dfdac40fe6716c743a437b70dbaa8924262b3fa5d5b50258fcf6a163ada089cc5c76b34b3bcd4ec148594b3db5f12888c8bca941898b8ae542d923e5",
    },
  })
  pages = response.data.data
  for (let page of addPages){
    router.removeRoute(page.Title)
  }
  for (let page of pages){
    addPages.push(page)
    router.addRoute({path: page.path, name: page.Title, sensitive: false, component: PageView})
  
  }
  
   let pageStore = await usePageStore()
   pageStore.pages = pages
}

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    }
  ],
})

router.beforeResolve( o => {
    let pageStore = usePageStore()
    pageStore.pages = pages
})


export default router
