require(['jquery', 'xwiki-meta'], function($, xm) {
  'use strict';
  const messages = ["Poor","Satisfactory","Good","Very good","Excellent"];
  const voteNumberMessage = "Votes";
  const postURL = new XWiki.Document('RatingsUIX', 'XWiki.Ratings').getURL('get');

  var setVote = function (wrapper, reference, vote, msgDiv) {
    var notification = new XWiki.widgets.Notification(
          "Your vote is being saved...",
          'inprogress'
        );
    $.post(postURL, {
      "outputSyntax": "plain",
      "vote": vote,
      "doc": reference,
      "form_token": xm.form_token
    }).done(function (data) {
      var averageVote = data.avgvote;
      var userVote = data.uservote;
      var totalVotes = data.totalvotes;
      if ((averageVote = parseFloat(averageVote))) {
        var width = averageVote * 20 + "%";
        wrapper.find('li.current-rating').first().width(width);
        msgDiv.text(totalVotes + " " + voteNumberMessage);
        // reset it to not obtain back and old message when using mouseout/mouseover
        msgDiv.previousMessage = "";
        notification.replace(new XWiki.widgets.Notification(
          "Your vote has been saved!",
          'done'
        ));
      } else {
        notification.replace(new XWiki.widgets.Notification(
          "Error when saving your vote.",
          'error'
        ));
      }
    }).fail(function (data) {
      notification.replace(new XWiki.widgets.Notification(
          "Error when saving your vote." + " " + data,
          'error'
        ));
    });
  };
  
  var initLink = function (index, element, msgDiv, reference, wrapper) {
    var link = $(element);
    msgDiv.previousMessage = "";
    link.on('click', function() { setVote(wrapper, reference, index + 1, msgDiv); });
    link.on('mouseout', function () {
      if (msgDiv.previousMessage != "") {
        msgDiv.text(msgDiv.previousMessage);
      }
    });
    link.on('mouseover', function () {
      if (msgDiv.previousMessage == "") {
        msgDiv.previousMessage = msgDiv.text();
      }
      msgDiv.text(messages[index]);
    });
  };
  
  var initRating = function () {
    var ratingWrapper = $(this);
    // Augment only the ratings which are not locked
    if (!ratingWrapper.hasClass('locked') && !ratingWrapper.hasClass('initialized')) {
      var reference = ratingWrapper.data('reference');
      var msgDiv = ratingWrapper.find('.rating-message').first();
      if (reference) {
        ratingWrapper.find('.star-rating').first().find('a').each(function (index, element) {
          initLink(index, element, msgDiv, reference, ratingWrapper);
        });
      }
      ratingWrapper.addClass('initialized');
    }
  };

  var init = function ()
  {
    $(".rating-wrapper").each(initRating);
  };

  $(document).ready(init);
  $(document).on('xwiki:dom:updated', init);
});
