const m = require('mithril')
const storageName = 'nfp_sites_filadelfia_web_logintoken'

const Authentication = {
  currentUser: null,
  isAdmin: false,
  loadingListeners: [],
  authListeners: [],

  updateToken: function(token) {
    if (!token) return Authentication.clearToken()
    localStorage.setItem(storageName, token)
    Authentication.currentUser = JSON.parse(atob(token.split('.')[1]))

    if (Authentication.authListeners.length) {
      Authentication.authListeners.forEach(function(x) { x(Authentication.currentUser) })
    }
  },

  clearToken: function() {
    Authentication.currentUser = null
    localStorage.removeItem(storageName)
    Authentication.isAdmin = false
  },

  addEvent: function(event) {
    Authentication.authListeners.push(event)
  },

  setAdmin: function(item) {
    Authentication.isAdmin = item
  },

  getToken: function() {
    return localStorage.getItem(storageName)
  },

  getTokenDecoded: function() {
    let token = Authentication.getToken()
    var base64Url = token.split('.')[1];
    var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
  
    return JSON.parse(jsonPayload);
  },

  requiresLogin: function() {
    if (Authentication.currentUser) return
    m.route.set('/login')
  },

  requiresNotLogin: function() {
    if (!Authentication.currentUser) return
    m.route.set('/')
  },
}

Authentication.updateToken(localStorage.getItem(storageName))

window.Authentication = Authentication

module.exports = Authentication
