export const IdentityMixin = {

  //@@viewOn:statics
  statics: {
    UU5_Common_IdentityMixin: {
      requiredMixins: ['UU5_Common_BaseMixin']
    }
  },
  //@@viewOff:statics

  //@@viewOn:propTypes
  //@@viewOff:propTypes

  //@@viewOn:getDefaultProps
  //@@viewOff:getDefaultProps

  //@@viewOn:standardComponentLifeCycle
  getInitialState: function () {
    // initialize
    this.registerMixin('UU5_Common_IdentityMixin');

    let Oidc;
    if (typeof window.System != "undefined" && window.System.has(window.System.normalizeSync("uu_oidc"))) {
      Oidc = window.System.get(window.System.normalizeSync("uu_oidc"));
      this._oidc = Oidc;
      if (Oidc) {
        Oidc.Session.currentSession.addIdentityChangeListener(this._onChangeIdentity);
      }
    }

    // state
    return {
      identity: Oidc ? Oidc.Session.currentSession.getIdentity() : {},
      isAuthenticated: Oidc ? Oidc.Session.currentSession.isAuthenticated() : false
    };
  },

  componentWillUnmount: function () {
    this.getCurrentSession() && this.getCurrentSession().removeIdentityChangeListener(this._onChangeIdentity);
  },
  //@@viewOff:standardComponentLifeCycle

  //@@viewOn:interface
  hasUU5_Common_IdentityMixin: function () {
    return this.hasMixin('UU5_Common_IdentityMixin');
  },

  getUU5_Common_IdentityMixinProps: function () {
    return {};
  },

  getUU5_Common_IdentityMixinPropsToPass: function () {
    return this.getUU5_Common_IdentityMixinProps();
  },

  getCurrentSession() {
    return this._oidc ? this._oidc.Session.currentSession : null;
  },

  login() {
    this.getCurrentSession().login();
    return this;
  },

  logout() {
    this.getCurrentSession().logout();
    return this;
  },

  isAuthenticated() {
    return this.state.isAuthenticated;
  },

  getIdentity() {
    return this.state.identity;
  },

  changeIdentity(setStateCallback) {
    this.getCurrentSession() && this.setState({
      identity: this.getCurrentSession().getIdentity(),
      isAuthenticated: this.getCurrentSession().isAuthenticated()
    }, setStateCallback);
    return this;
  },
  //@@viewOff:interface

  //@@viewOn:overridingMethods
  //@@viewOff:overridingMethods

  //@@viewOn:componentSpecificHelpers
  _onChangeIdentity() {
    if (this.getCurrentSession()) {
      if (typeof this.onChangeIdentity_ === 'function') {
        this.onChangeIdentity_(this.getCurrentSession());
      } else {
        this.changeIdentity();
      }
    }
    return this;
  }
  //@@viewOff:componentSpecificHelpers
};

export default IdentityMixin;
