// this is image_share.js
Images = new Mongo.Collection("images");

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

  Template.images.helpers({
    images: Images.find({}, { sort: { createdOn: -1, rating: -1 }}),
    image_id: function () {
      return "rating-" + this._id;
    }
  });

  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 (event) {
      $("#image_add_form").modal("show");
    }

  });

  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);

      Images.insert({
        img_src: img_src,
        img_alt: img_alt,
        createdOn: new Date()
      });
       $("#image_add_form").modal('show');
      return false;
    }
  });
}
