import {
  getHeader,
  isServer,
  queryOrCookieStrToObj,
  getNextConfig
} from '$ustoreinternal/services/utils'
import { routes } from '$routes'
import { USER_ID_EXPIRATION_DAYS } from '$ustoreinternal/services/initialLoad'
import { CookiesManager, storefrontCookies } from '$ustoreinternal/services/cookies'
import { UStoreProvider } from '@ustore/core'

const publicRuntimeConfig = getNextConfig()

class ThemeContext {
  constructor() {
    this.context = { ...publicRuntimeConfig, ...{ page: 'home' } }
  }

  get(key) {
    return key ? this.context[key] : this.context
  }

  set(key, value) {
    this.context[key] = value
  }

  deleteKey(key) {
    delete this.context[key]
  }

  updateRouteParams(ctx) {
    const asPath = ctx ? ctx.asPath : window.location.pathname

    this.set('page', 'home')
    this.deleteKey('id')

    routes.forEach(r => {
      const m = r.match(asPath.split('?')[0])
      if (m) {
        Object.assign(this.context, m)
      }
    })
  }

  // init the application context in the follow uses cases:
  // 1. in the server from the request then use the requests header fields
  // 2. in the server from the url which will override the header fields
  // 3. in the client only from the query string
  // 4. in the client only from the cookies (cookies are using also inserted to the request header)
  init(ctx) {

    if (ctx) {
      if (ctx.req) {

        this.context.securityToken = getHeader(ctx.req, storefrontCookies.token)
        this.context.languageCode = getHeader(ctx.req, storefrontCookies.language + `_${ctx.query.storeFriendlyID}`)
        this.context.storeID = getHeader(ctx.req, storefrontCookies.storeID)
        this.context.currencyFriendlyID = getHeader(ctx.req, storefrontCookies.currencyID)
        this.context.userID = getHeader(ctx.req, storefrontCookies.userID)
        this.context.currencyID = getHeader(ctx.req, storefrontCookies.currencyGUID)
        this.context.cartUrl = getHeader(ctx.req, storefrontCookies.cartUrl)
        this.context.logoutUrl = getHeader(ctx.req, storefrontCookies.logoutUrl)
      }
      if (ctx.query) {

        ctx.query.SecurityToken && (this.context.securityToken = ctx.query.SecurityToken)
        ctx.query.languageCode && (this.context.languageCode = ctx.query.languageCode)
        ctx.query.StoreGuid && (this.context.storeID = ctx.query.StoreGuid)
        ctx.query.currencyFriendlyID && (this.context.currencyFriendlyID = ctx.query.currencyFriendlyID)
        ctx.query.UserID && (this.context.userID = ctx.query.UserID)
        ctx.query.currencyID && (this.context.currencyID = ctx.query.currencyID)
        ctx.query.cartUrl && (this.context.cartUrl = ctx.query.cartUrl)
        ctx.query.logoutUrl && (this.context.logoutUrl = ctx.query.logoutUrl)
      }
    } else {
      const searchStr = window.location.search.substring(1)

      if (searchStr) {
        const q = queryOrCookieStrToObj(searchStr)

        if (q.SecurityToken) {
          this.context.securityToken = q.SecurityToken
          CookiesManager.setCookie({ key: storefrontCookies.token, value: this.context.securityToken })
        }

        if (q.CultureCode) {
          this.context.languageCode = q.CultureCode
        }

        if (q.StoreGuid) {
          this.context.storeID = q.StoreGuid
          CookiesManager.setCookie({ key: storefrontCookies.storeID, value: this.context.storeID })
        }

        if (q.currencyFriendlyID) {
          this.context.currencyFriendlyID = q.currencyFriendlyID
        }

        if (q.UserID) {
          this.context.userID = q.UserID
          CookiesManager.setCookie({ key: storefrontCookies.userID, value: this.context.userID, days: USER_ID_EXPIRATION_DAYS })
        }

        if (q.ShowRibbon) {
          UStoreProvider.state.customState.set('showCookieRibbon', (q.ShowRibbon.toLowerCase() === 'true'))
          CookiesManager.setCookie({ key: storefrontCookies.cookieRibbonNotShownYet, value: q.ShowRibbon.toLowerCase() })
        }

        if (q.CurrencyID) {
          UStoreProvider.state.customState.set('currencyID', (q.CurrencyID))
          this.context.currencyID = q.CurrencyID
        }

        if (q.cartUrl) {
          UStoreProvider.state.customState.set('cartUrl', (q.cartUrl))
          this.context.cartUrl = q.cartUrl
          CookiesManager.setCookie({ key: storefrontCookies.cartUrl, value: q.cartUrl })
        }

        if (q.logoutUrl) {
          UStoreProvider.state.customState.set('logoutUrl', (q.logoutUrl))
          this.context.logoutUrl = q.logoutUrl
          CookiesManager.setCookie({ key: storefrontCookies.logoutUrl, value: q.logoutUrl })
        }

      }

      this.context.languageCode =   CookiesManager.getCookie(storefrontCookies.language) || this.context.languageCode
      this.context.showThemeAsDraft =   CookiesManager.getCookie(storefrontCookies.showThemeAsDraft) || this.context.showThemeAsDraft
      this.context.securityToken =   CookiesManager.getCookie(storefrontCookies.token) || this.context.securityToken
      this.context.storeID =   CookiesManager.getCookie(storefrontCookies.storeID) || this.context.storeID
      this.context.currencyFriendlyID =   CookiesManager.getCookie(storefrontCookies.currencyID) || this.context.currencyFriendlyID
      this.context.userID =   CookiesManager.getCookie(storefrontCookies.userID) || this.context.userID

      this.context.CurrencyID =   CookiesManager.getCookie(storefrontCookies.currencyGUID) || this.context.CurrencyID
      this.context.cartUrl =   CookiesManager.getCookie(storefrontCookies.cartUrl) || this.context.cartUrl
      this.context.logoutUrl =   CookiesManager.getCookie(storefrontCookies.logoutUrl) || this.context.logoutUrl

    }

    if (UStoreProvider.state.get() && UStoreProvider.state.get().currentUser) {
      this.context.userID = UStoreProvider.state.get().currentUser.ID
      if (!isServer()) CookiesManager.setCookie({ key: storefrontCookies.userID, value: this.context.userID, days: USER_ID_EXPIRATION_DAYS })
      if (ctx && ctx.query) ctx.query.UserID = UStoreProvider.state.get().currentUser.ID

    }

    const asPath = isServer() ? ctx.req.path : window.location.pathname

    // analise the routes and extract the route variables (i.e ':page')
    routes.forEach(r => {
      const m = r.match(asPath.split('?')[0])

      if (m) {
        this.context = Object.assign({}, this.context, m)
      }
    })

  }


}

export default new ThemeContext()
