var initialize = function() {

var opts = $('#js-notifications-container');

if (opts.length == 0) {
  return;
}

if (firebase.apps.length === 0) {
  var config = {
    apiKey:      `${opts.data('firebase-api-key')}`,
    authDomain:  `${opts.data('firebase-project-id')}.firebaseapp.com/`,
    databaseURL: `https://${opts.data('firebase-project-id')}.firebaseio.com/`,
  };

  firebase.initializeApp(config);
}

var destination = opts.data('destination');

var ref = firebase
  .database()
  .ref(`notifications/${destination}`);

ref.off();

ref
  .orderByChild('read_at')
  .equalTo(false)
  .on('child_added', onNotificationAdded.bind(this));

};

var onNotificationAdded = function(notification) {

var value = notification.val();
var key   = notification.key;

appendNotification(value, key);
setNotificationsCount();

}

var appendNotification = function(notification, key) {

var container = $('#js-notifications-container');

var notification_container       = container.data('notification-container');
var notification_container_class = container.data('notification-container-class');
var notification_class           = container.data('notification-class');

var id = 'js-notification-' + Math.random().toString(36).substr(2, 9)

var html = "" +
  "<" + notification_container + " class='" + notification_container_class +"' id='" + id +"'>" +
    "<a href='" + notification.link + "'>" +
      "<span class='js-notification " + notification_class + "'>" +
        notification.text +
      "</span>" +
    "</a>" +
  "</" + notification_container + ">"

container.prepend(html);
bindOnClickListener(id, key, notification);

};

var bindOnClickListener = function(html_id, key, notification) {

var opts = $('#js-notifications-container');

$('#' + html_id).on('click', function() {
  firebase
    .database()
    .ref(`notifications/${opts.data('destination')}`)
    .child(key)
    .update({
      read_at: Date.now()
    });
});

};

var setNotificationsCount = function() {

var container = $('#js-notifications-count');

if (container.length == 0){
  return;
}

container.text($('.js-notification').length);

};

$(document).ready(initialize); // No Turbolinks $(document).on('page:load', initialize); // Rails <= 4 $(document).on('turbolinks:load', initialize); // Rails 5