/*jshint eqnull:true, browser:true */
/*global URI:true */
//
// Twitch.emailNotifier
//
// The purpose of this library is to bug unverified users to give us their email address

(function (Twitch, $) {
  var emailNotifier = {};

  emailNotifier.init = function (config) {
    this.config = Twitch.defaults(config, {
      forgetDuration: config.forgetDuration,
      delay: config.delay
    });

    var timeSinceAsked = Number.POSITIVE_INFINITY;

    var lastEmailRequest = parseInt(Twitch.storage.get("requestUserEmail"), 10);
    if (!isNaN(lastEmailRequest)) {
      timeSinceAsked = +new Date() - lastEmailRequest;
    }
    if (timeSinceAsked > this.config.forgetDuration * 1000) {
      setTimeout(Twitch.emailNotifier.requestUserEmail, this.config.delay * 1000);
    }
  };

  emailNotifier.requestUserEmail = function () {
    var notifyOpts = {
      timeout: 20000,
      escape: false
    };
    Twitch.storage.set("requestUserEmail",  +new Date());
    Twitch.api.get('user').done(function (data) {
      var path = URI(window.location.href).path();
      if (!data.email && path !== "/settings") {
        Twitch.tracking.mixpanel.trackEvent("email_notice", {type: "display"});
        Twitch.notify('Welcome to Twitch! <a href="/settings?type=email_notice">' +
          'Please click here to verify your email! </a>',
          notifyOpts);
      }
    });
  };

  Twitch.mixin({
    emailNotifier: emailNotifier
  });

})(Twitch, jQuery);
