import Views from '../templates/Views'

export default class RouteController {

  constructor () {
    document.addEventListener('DOMContentLoaded', e => {
      this._navigation()
      this._history()
    })
  }

  get routes () {
    return window.env.routes
  }

  /**
   *
   * @returns {*}
   */
  get navbar () {
    return document.getElementById(window.env.querySelectors.navTabs.slice(1))
  }

  get page404(){
    document.body.innerHTML = Views.templates.notFound
    setTimeout( () => {
      window.location.assign('/')
    }, 5000)
  }

  /**
   *
   * @private
   */
  _navigation(){

    if( Object.keys(this.routes).filter( path => window.location.pathname === path ).length === 0 ){
        this.page404
    } else{
      document.querySelector( `a[href='${window.location.pathname}']` ).click()
    }

  }

  _history(){
    window.addEventListener('popstate', event => {
      try {
        document.querySelector('.uk-active').classList.remove('uk-active')
        document.querySelector(window.env.querySelectors.navTabs + ` a[href='${event.target.location.pathname}']`).closest('.nav-tab').classList.add('uk-active')
      } catch (e) {}

    })
  }

}