import Oidc from 'oidc-client'
import oidcMetadata from './oidc-metadata'

var mgr = process.env.VUE_APP_ONLY_SSO === 'true' ? new Oidc.UserManager({
  userStore: new Oidc.WebStorageStateStore({ store: window.localStorage }),
  // authority: process.env.VUE_APP_AUTH_SERVER,
  authority: 'x',
  client_id: process.env.VUE_APP_AUTH_CLIENT_ID,
  client_secret: process.env.VUE_APP_AUTH_CLIENT_SECRET,
  redirect_uri: window.location.origin + process.env.VUE_APP_PATH_BASE + 'signin-oidc',
  metadata: oidcMetadata,
  response_type: 'code',
  scope: 'openid profile BackboneService',
  post_logout_redirect_uri: window.location.origin + process.env.VUE_APP_PATH_BASE + 'signout-callback-oidc',
  accessTokenExpiringNotificationTime: 10,

  // silent renew will get a new access_token via an iframe
  // just prior to the old access_token expiring (60 seconds prior)
  silent_redirect_uri: window.location.origin + process.env.VUE_APP_PATH_BASE + 'silent-signin-oidc',
  automaticSilentRenew: true,

  // will revoke (reference) access tokens at logout time
  revokeAccessTokenOnSignout: true,

  filterProtocolClaims: true,
  loadUserInfo: true
}) : null

Oidc.Log.logger = console
Oidc.Log.level = Oidc.Log.INFO

if (mgr != null) {
  mgr.events.addUserLoaded(function(user) {
    console.log('New User Loaded：', arguments)
    console.log('Acess_token: ', user.access_token)
  })

  mgr.events.addAccessTokenExpiring(function() {
    console.log('AccessToken Expiring：', arguments)
  })

  mgr.events.addAccessTokenExpired(function() {
    console.log('AccessToken Expired：', arguments)
    // alert("Session expired. Going out!");
    mgr
      .signoutRedirect()
      .then(function(resp) {
        console.log('signed out', resp)
      })
      .catch(function(err) {
        console.log(err)
      })
  })

  mgr.events.addSilentRenewError(function() {
    console.error('Silent Renew Error：', arguments)
  })

  mgr.events.addUserSignedOut(function() {
  // alert("Going out!");
    console.log('UserSignedOut：', arguments)
    mgr
      .signoutRedirect()
      .then(function(resp) {
        console.log('signed out', resp)
      })
      .catch(function(err) {
        console.log(err)
      })
  })
}

export default class AuthService {
  // Renew the token manually
  async renewToken() {
    var user = await mgr.signinSilent()
    if (user == null) {
      this.signIn(null)
    }
    return user
  }

  // 获取已登陆用户的认证信息
  async getUser() {
    var user = await mgr.getUser()
    return user
  }

  // 确保当前用户已登陆
  async ensureSignedIn() {
    var user = await mgr.getUser()
    if (user == null) {
      await this.signIn()
    }
    return user
  }

  // Redirect of the current window to the authorization endpoint.
  async signIn() {
    await mgr.signinRedirect()
  }

  async signinRedirectCallback() {
    var user = await mgr.signinRedirectCallback()
    return user
  }

  // Redirect of the current window to the end session endpoint
  async signOut() {
    try {
      var resp = await mgr
        .signoutRedirect()
      console.log('signed out', resp)
    } catch (err) {
      console.log(err)
    }
  }

  // Get the profile of the user logged in
  async getProfile() {
    var user = await mgr.getUser()
    if (user == null) {
      this.signIn()
      return null
    }
    return user
  }

  // Get the token id
  async getIdToken() {
    var user = await mgr.getUser()
    if (user == null) {
      this.signIn()
      return null
    }
    return user.id_token
  }

  // Get the session state
  async getSessionState() {
    var user = await mgr.getUser()
    if (user == null) {
      this.signIn()
      return null
    }
    return user.session_state
  }

  // Get the access token of the logged in user
  async getAccessToken() {
    var user = await mgr.getUser()
    if (user == null) {
      this.signIn()
      return null
    }
    return user.access_token
  }

  // Takes the scopes of the logged in user
  async getScopes() {
    var user = await mgr.getUser()
    if (user == null) {
      this.signIn()
      return null
    }
    return user.scopes
  }

  // Get the user roles logged in
  async getRole() {
    var user = await mgr.getUser()
    if (user == null) {
      this.signIn()
      return null
    }
    return user.profile.rol
  }
}
