Session.set("imageLimit", 8);

let lastScrollTop = 0;

$(window).scroll(function (event) {
  let $window = $(window);

  // Current position in the page.
  let scrollTop = $window.scrollTop();

  // If we are near the bottom of the window.
  if (scrollTop + $window.height() > $(document).height() - 100) {
    // If we are heading down.
    if (scrollTop > lastScrollTop) {
      Session.set("imageLimit", Session.get("imageLimit") + 4);
      console.log('Increased image count');
    }
    lastScrollTop = scrollTop;
  }
});

Accounts.ui.config({
  passwordSignupFields: "USERNAME_AND_EMAIL"
});

const getUser = (userId) => {
  let user = Meteor.users.findOne({ _id: userId });
  return user ? user.username : "anonymous";
};

Template.images.helpers({ getUser,
  images: function () {
    const createdBy = Session.get("userFilter");
    const selector = createdBy ? { createdBy } : {};
    return Images.find(selector, {
      sort: { createdOn: -1, rating: -1 },
      limit: Session.get("imageLimit")
    });
  },
  filtering_images: function () {
    const userFilter = Session.get("userFilter");
    return !!userFilter;
  },
  image_id: function () {
    return "rating-" + this._id;
  },
  getFilterUser: function () {
    const userFilter = Session.get("userFilter");
    return getUser(userFilter);
  }
});

Template.body.helpers({
  username: function () {
    let user = Meteor.user();
    let name = user ? user.username : "anon";
    return name;
  }
});

Template.images.events({
  "click .js-image": function (event) {
    $(event.target).css("width", "50px");
  },
  "click .js-del-image": function (event) {
    let imageId = this._id;
    console.log(imageId);
    // use jquery to hide the image component
    // then remove it at the end of the animation
    $("#" + imageId).hide("slow", function () {
      Images.remove({ _id: imageId });
    });
  },
  "click .js-rate-image": function (event) {
    let rating = $(event.currentTarget).data("userrating");
    let imageId = this.id.substring(7); // "rating-".length = 7.
    console.log(imageId);

    Images.update({ _id: imageId },
      { $set: { rating: rating }}
    );
  },
  "click .js-show-image-form": function () {
    $("#image_add_form").modal("show");
  },
  "click .js-set-image-filter": function () {
    Session.set("userFilter", this.createdBy);
  },
  "click .js-unset-image-filter": () => {
    Session.delete("userFilter");
  }
});

Template.image_add_form.events({
  'submit .js-add-image': function (event) {
    let img_src = event.target.img_src.value;
    let img_alt = event.target.img_alt.value;
    console.log("src: " + img_src + " alt: " + img_alt);

    if (Meteor.user()) {
      Images.insert({
        img_src: img_src,
        img_alt: img_alt,
        createdOn: new Date(),
        createdBy: Meteor.userId()
      });
    }
    $("#image_add_form").modal("hide");
    return false;
  }
});
