import Vue from 'vue'
import VueRouter, { RouterMode } from 'vue-router'
import { PositionResult } from 'vue-router/types/router'

import { IMyRoute, IMyRouteRecord, cfgrouter } from './route-config'
import { ProgressBar } from '@src/store/Modules/Interface'
import { isEqual } from 'lodash'
import { GlobalStore, UserStore } from '@store'
import { tools } from '@src/store/Modules/tools'
import { toolsext } from '@src/store/Modules/toolsext'
import { static_data } from '@src/db/static_data'

Vue.use(VueRouter)
/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation
 */

let TIMER = null
let URL_RITORNA = ''
let TIMER_STATE = 0
let URL_RESTORE = ''

const Router = new VueRouter({
  scrollBehavior: () => ({ x: 0, y: 0 } as PositionResult),
  routes: cfgrouter.getmenu(),

  // Leave these as is and change from quasar.conf.js instead!
  // quasar.conf.js -> build -> vueRouterMode
  mode: process.env.VUE_ROUTER_MODE as RouterMode,
  base: process.env.VUE_ROUTER_BASE
})

function nextFactory(context, middleware, index) {
  const subsequentMiddleware = middleware[index]
  // If no subsequent Middleware exists,
  // the default `next()` callback is returned.
  if (!subsequentMiddleware) {
    return context.next
  }

  return (...parameters) => {
    // Run the default Vue Router `next()` callback first.
    context.next(...parameters)
    // Then run the subsequent Middleware with a new
    // `nextMiddleware()` callback.
    const nextMiddleware = nextFactory(context, middleware, index + 1)
    subsequentMiddleware({ ...context, next: nextMiddleware })
  }
}

Router.beforeEach(async (to: IMyRoute, from: IMyRoute, next) => {
    try {
      // Check session
      // if (!LoginStore.state.sessionChecked) {
      //   await LoginStore.actions.checkUserSession();
      // }

      /*
            if (!from || !to || from.matched.length <= 0) {
              next()
              return
            }
      */
      // console.log('LOAD from e to: ', from, to)

      if (!!GlobalStore) {
        if (!GlobalStore.state.finishLoading) {

          let eseguicheck = true

          // Controlla se c'è nella lista allora non eseguire il controllo:
          for (const route of static_data.routes) {
            if (route.path === to.path) {
              eseguicheck = false
              break
            }
          }

          if (eseguicheck) {
            // Qui arrivano gli URL che non sono della lista ROUTE.
            // quindi ad esempio http://localhost:8085/signup/paoloar77

            if (!TIMER && to.path !== '/') {
              // console.log('TIMER')
              TIMER = setInterval(() => {
                // console.log('SETINTERVAL')
                if (GlobalStore.state.finishLoading) {
                  if (!!TIMER) {
                    // console.log('TIMER_STATE', TIMER_STATE, 'URL_RITORNA', URL_RITORNA)
                    if (TIMER_STATE === 2) {
                      clearInterval(TIMER)
                      TIMER = null
                      // console.log('TERMINA INTERVALLO')
                      // next('/prova')
                      // return
                    }
                    // se mi ero salvato un url per doverci ritornare, allora puntalo a questo:
                    if (URL_RITORNA !== '') {
                      // next(URL_RITORNA)
                      TIMER_STATE = 2
                      return
                    } else {
                      if (TIMER_STATE === 0) {
                        URL_RESTORE = to.path
                        //  next('/')
                        TIMER_STATE = 1
                        return
                      }
                    }
                  }
                }
              }, 200)
            }
          }

        }
        if (GlobalStore.state.finishLoading) {
          if (!!TIMER) {
            // console.log('TIMER_STATE', TIMER_STATE, 'to.path', to.path)
            if (URL_RITORNA === '' && URL_RESTORE !== '') {
              URL_RITORNA = URL_RESTORE
              // onsole.log('URL_RITORNA', URL_RITORNA)
            }
          }
        }

        // await tools.aspettansec(4000)

      }


      if (from.name && from.matched[0].name === to.name && from.meta.isModal) {
        next()
        console.log('Route interceptor log: <1>')
        return
      }
      else if (from.name === to.name && isEqual(from.params, to.params)) {
        console.log('Route interceptor log: <2>')
        console.log('from e to: ', from, to)
        next()
      } else {
        if (!to.meta.transparent && !to.meta.isModal) {
          // console.log('Route interceptor log: <4>')
          ProgressBar.mutations.start()
        }
        else if (to.meta.transparent && !from.name) {
          console.log('Route interceptor log: <5>')
          ProgressBar.mutations.start()
        }
        else if (to.meta.transparent && !to.matched.some((m) => m.name === from.name)) {
          console.log('Route interceptor log: <6>')
          ProgressBar.mutations.start()
        }

        // If page is initialazed on child
        /*
                  if (to.matched[0] && to.meta.isModal) {
                    console.log('Route interceptor log: <7>')
                    if (!from.nametranslate) {
                      getRouteData(to.matched[0])
                      GlobalStore.mutations.setPreviousModalRoute(to.matched[0].path)
                    } else {
                      GlobalStore.mutations.setPreviousModalRoute(from.fullPath)
                    }
                  }
        */


        // Check requires auth
        if (to.matched.some((m) => m.meta.requiresAuth)) {
          // await LoginStore.actions.refreshUserInfos()
          if (tools.isLoggedToSystem()) {
            if (!!to.meta.asyncData) {
              await getRouteData(to)
            }
            /*
            if (to.matched.some((m) => !!m.meta.isAuthorized)) {
            const results = await Promise.all([
                ...to.matched.filter((m) => !!m.meta.isAuthorized)
                  .map((m) => m.meta.isAuthorized(to))
              ])

                        if (!results.every((m) => m)) {
                          NotificationsStore.actions.addNotification({
                            type: 'warning',
                            message: `Vous n'avez pas accès à cette page`
                          })
                          ProgressBar.mutations.fail()
                          if (from.nametranslate) {
                            return
                          } else {
                            next('/')
                          }
                        }
            }
            */
          } else {
            // LoginStore.mutations.showLoginRoute(to.fullPath)
            if (from.name) {
              ProgressBar.mutations.hide()
            } else {
              // next('/')
            }

            return Router.push({ name: 'pages.SignIn' })
          }
        } else if (to.matched.some((m) => m.meta.noAuth) && UserStore.state.isLogged) {
          next('/')
        } else {
          if (!!to.meta.asyncData) {
            await getRouteData(to)
          }
        }
      }

      // if (to.meta.middleware) {
      //   const middleware = Array.isArray(to.meta.middleware)
      //     ? to.meta.middleware
      //     : [to.meta.middleware]
      //
      //   const context = {
      //     from,
      //     next,
      //     Router,
      //     to
      //   }
      //
      //   const nextMiddleware = nextFactory(context, middleware, 1)
      //
      //   return middleware[0]({ ...context, next: nextMiddleware })
      // }
      //
      return next()

    }
    catch
      (err) {
      console.log('Route error:', err)
      ProgressBar.mutations.fail()
    }
  }
)

const getRouteData = async (to: IMyRoute | IMyRouteRecord) => {
  if (!to.meta.transparent) {
    ProgressBar.mutations.start()
  }
  const titleToDisplay: any = await to.meta.asyncData(to)
  // if (to.meta.contentProp) {
  //   document.title = `${titleToDisplay.title || to.meta.title} - MovingMate`
  // }
}

Router.afterEach(async (from: IMyRoute, next) => {
  ProgressBar.mutations.finish()
  // AlertsStore.mutations.hideAlert()
  // EventBus.$emit('closePopups')
})

export default Router
