/* global URI */
/*jshint sub:true*/

(function ($) {
  window.NotificationsTracker = {
    startTracking: function () {
      /* Naive check to prevent sitewide notifications on embed channels and chat
        Currently, twitch.tv/embed fails to load, and twitch.tv/chat is TOS banned
        So this appears to be okay. */
      var filename = URI().filename();
      if (filename === 'embed' || filename === 'chat') {
        return;
      }
      var notifications = {};
      var messageNotification;

      var DISMISSED_IDS_LOCALSTORAGE_KEY = 'Notifications:Dismissed';
      var POPUP_OPTIONS = {
        layout: 'bottomCenter',
        timeout: false,
        escape: false,
        animation: {
          open: {
            height: 'toggle'
          },
          close: {
            height: 'toggle'
          },
          easing: 'swing',
          speed: 150
        }
      };
      var MESSAGE_OPTIONS = _.defaults({
        timeout: 5000,
        escape: false
      }, POPUP_OPTIONS);

      var dismiss = function (id) {
        var dismissedIds = Twitch.storage.getObject(DISMISSED_IDS_LOCALSTORAGE_KEY) || [];
        dismissedIds.push(id);
        Twitch.storage.setObject(DISMISSED_IDS_LOCALSTORAGE_KEY, dismissedIds);
      };

      var dismissed = function (id) {
        var dismissedIds = Twitch.storage.getObject(DISMISSED_IDS_LOCALSTORAGE_KEY) || [];
        return _.contains(dismissedIds, id);
      };

      var addNotification = function (id, type, message) {
        if (!dismissed(id)) {
          notifications[id] = Twitch.notify[type](message, POPUP_OPTIONS, function () {
            dismiss(id);
          });
        }
      };

      // Don't notify on the first-connect message (only notify new messages)
      var addUnreadMessageNotification = _.after(2, function (messageSHA) {
        if (messageSHA) {
          if (messageNotification) {
            // Notification is already up.  Replace notification text with inbox link.
            messageNotification.setText('You have <a href="/messages/inbox">new messages</a>!');
          } else {
            // Notification is not shown.  Show notification with message link.
            var message = 'You have a <a href="' + Twitch.uri.message(messageSHA) + '">new message</a>!';
            messageNotification = Twitch.notify.alert(message, MESSAGE_OPTIONS, function () {
              messageNotification = null;
            });
          }
        }
      });

      // Display the notifications for the current user's roles
      var displayNotifications = function (roles) {
        Twitch.api.get('/api/notifications').then(function (notificationList) {
          _.each(roles, function (role) {
            _.each(notificationList[role], function (notification, id) {
              addNotification(id, notification.type, notification.message);
            });
          });
        });
      };

      // Collect roles for the current user and then display notifications
      var roles = ['everyone'];
      if (Twitch.user.isLoggedIn()) {
        Twitch.user(function (userData) {
          // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
          if (userData.is_partner) {
            roles.push('partners');
          }
          if (userData.is_broadcaster && userData.last_broadcast_time) {
            var MONTH_IN_MILLISECONDS = 2628000000;
            var difference = (new Date()).getTime() - new Date(userData.last_broadcast_time).getTime();
            if (difference < MONTH_IN_MILLISECONDS) {
              roles.push('recent_broadcasters');
            }
          }
          displayNotifications(roles);
          // jscs:enable requireCamelCaseOrUpperCaseIdentifiers
        }, function () {
          displayNotifications(roles);
        });
      } else {
        displayNotifications(roles);
      }

    }
  };

})(jQuery);
