justinhelmer
8/16/2017 - 10:09 PM

bt.js

const wrap = (cb) => {
  if (ENV_CONFIG.brighttag_enabled !== 'on') return _.noop;
  return cb;
};

var dataDictionary = {
  prefix: 'MEW_',
  loadingData: false,
  loadUserDataFromModel: wrap(function(){
    if (!this.loadingData){
      this.loadingData = true;
      this.userProfileModel = new UserProfileModel();
      this.userProfileModel.listenTo(this.userProfileModel, 'modelready', _.bind(this.userDataSuccess, this));
      this.userProfileModel.listenTo(this.userProfileModel, 'fetchError', this.userDataFailure);
      this.userProfileModel.fetch();
    }
  }),

  userDataSuccess: wrap(function(){
    var userId = (this.userProfileModel && this.userProfileModel.get('user') && this.userProfileModel.get('user').loginCredentials && this.userProfileModel.get('user').loginCredentials.userName) ? this.userProfileModel.get('user').loginCredentials.userName : '';
    if ( userId){
      this.saveUserHashedEmail(userId);
    }
    this.loadingData = false;
  }),

  userDataFailure: wrap(function(){
    this.loadingData = false;
  }),

  getDataDictionary: wrap(function() {
    if (_.isUndefined (window.MACYS)){
      window.MACYS = {};
    }

    if( _.isUndefined( window.MACYS.brightTag)){
      window.MACYS.brightTag = {};
    }

    return window.MACYS.brightTag;
  }),

  clearAll: wrap(function() {
    var dd = this.getDataDictionary();
    if(dd.navigation){
      delete dd.navigation;
    }
  }),

  clearEmailInformation: wrap(function(){
    var dd = this.getDataDictionary();
    if(dd.hE2){
      $sessionStorage.remove('BTDataAttrHE2');
      delete dd.hE2;
    }
    if(dd.hE){
      $sessionStorage.remove('BTDataAttrHE');
      delete dd.hE;
    }
  }),

  setNavigation: wrap(function( pageName, pageId) {
    var dd = this.getDataDictionary();

    this.clearAll();

    dd.navigation = {
      pageName: this.prefix + pageName,
      pageID: this.prefix + pageId
    };
  }),

  setHashedEmail: wrap(function() {
    var dd  = this.getDataDictionary(),
        hE  = $sessionStorage.get('BTDataAttrHE'),
        hE2 = $sessionStorage.get('BTDataAttrHE2');
    if(hE && hE2){
      dd.hE2 = hE2;
      dd.hE = hE;
    }
    else{
      this.loadUserDataFromModel();
    }
  }),
  
  saveUserHashedEmail: wrap(function(userEmail){
    $sessionStorage.set('BTDataAttrHE', sha256.sha256(userEmail));
    $sessionStorage.set('BTDataAttrHE2', sha256.sha256(md5(userEmail)));
    this.setHashedEmail();
  })
};