var SocialNetworkFormPlanner = (function() {
  var socialNetworkPlanner = new SocialNetworkPlanner();
  var editStringSelector   = '[data-queue-edit-planner]';
  var createStringSelector = '[data-queue-add-planner]';

  var bindEdit = function() {
    $('body').on('click', editStringSelector, function(e){
      e.preventDefault();

      var eventData    = $(this).data('queueEditPlanner');
      var options      = {
        onEditCallBack: function(data) {
          $('[data-queue-id="'+data.element.id+'"]').replaceWith(buildRow(data));
        },
        onDeleteCallback: function (data) {
          $('[data-queue-id="'+data.element.id+'"]').remove();
          updateCounterMessage();
        },
        displayInterval: eventData.displayInterval,
        displayFutureInfoShape: false,
        forcedStartDate: eventData.forcedStartDate
      };

      socialNetworkPlanner.triggerEdit(eventData, options);
    });
  };

  var bindCreate = function () {
    $('body').on('click', createStringSelector, function(e){
      e.preventDefault();

      var eventData    = $(this).data('queueAddPlanner');
      var eventOptions = $(this).data('queueAddPlannerOptions');
      var options      = Object.assign(eventOptions, {
        onCreateCallback: function(data) {
          $('[data-queue-container]').append(buildRow(data));
          updateCounterMessage();
        }
      });

      socialNetworkPlanner.triggerCreate(eventData, options);
    });
  };

  var buildRow = function(data) {
    var profiles = '';
    var date     = data.response.data.start ? moment(data.response.data.start).format("HH:mm DD/MM/YYYY") : Translator.trans('social_network.info.no_date');
    var message  = data.response.data.message.message ? data.response.data.message.message : Translator.trans('social_network.planner.in_process_message');

    $.each(data.response.data.profiles, function(k, profile){
      profiles += '<i class="fa fa-'+ profile.name +'" style="color:'+ profile.color +'"></i>';
    });

    return $('<div class="content-socialNetworks-queue-item"  data-queue-id="'+ data.response.data.id +'">' +
      '<a href="#" data-queue-edit-planner=\''+JSON.stringify(data.response.data)+'\'>\n' +
      '<span>'+ message +'</span>\n' +
      '<span>'+ date + '</span>' +
      '<span>' + profiles + '</span>\n' +
      '</a>\n' +
      '</div>'
    );
  };

  var updateCounterMessage = function() {
    var count   = $('[data-queue-edit-planner]').length;

    var message = Translator.transChoice('social_network.info.planned_info', count, {'socialNetworkQueues' : count});

    $('#queue-counter').html(message);
  };

  return {
    init: function() {
      bindCreate();
      bindEdit();
    }
  };
})();
