/*jshint eqeqeq:false, eqnull:true, browser:true, bitwise:false */
/*global console,Crypto,CryptoJS,cookie*/

// = require cookie
// = require crypto-sha1

/**
 * Produces and accesses user identifiers.
 * These Ids are cached in the cookies of the user.
 *
 *  Note that for now this only contains unique_id and feature bucket.
 *
 */
(function (Twitch, $) {
  var identifiers = {};

  identifiers._generateRandomString = function (len) {
    var str = new Array(len);
    for (var i = 0; i < len; i++) {
      str[i] = String.fromCharCode(Math.floor(Math.random() * 27) + 65);
    }
    return str.join("");
  };

  identifiers.createUniqueId = function (seedString) {
    var seed = seedString || "";
    seed += this._generateRandomString(32) + new Date().toLocaleTimeString();
    return CryptoJS.SHA1(seed).toString().substring(0, 16);
  };

  // TODO we might want to double check in the flash cookies
  identifiers.getOrCreateUniqueId = function () {
    if (!cookie.get("unique_id")) {
      cookie.set("unique_id", this.createUniqueId(), {
        expires: 3650 // expires in 10 years
      });
    }

    return cookie.get("unique_id");
  };

  identifiers.getOrCreateSessionUniqueId = function () {
    if (!cookie.get("session_unique_id")) {
      cookie.set("session_unique_id", this.createUniqueId());
    }

    return cookie.get("session_unique_id");
  };

  identifiers.getOrCreateLocalStorageUniqueId = function () {
    if (!Twitch.storage.get('localstorage_unique_id')) {
      Twitch.storage.set('localstorage_unique_id', this.createUniqueId());
    }

    return Twitch.storage.get('localstorage_unique_id');
  };

  identifiers.getOrCreateSessionStorageUniqueId = function () {
    var uid = Twitch.storage.get('sessionstorage_unique_id', {storage: 'sessionStorage'});

    if (!uid) {
      uid = this.createUniqueId();
      Twitch.storage.set('sessionstorage_unique_id', uid, {storage: 'sessionStorage'});
    }

    return uid;
  };

  Twitch.mixin({
    idsForMixpanel: identifiers
  });

})(Twitch, jQuery);
