App.PhotoPreview = {
  init: function(element) {
    var fileInput = $(element).data("file-input");

    // Listen for changes on the file input field
    $(fileInput).on("change", function(e) {
      var input = e.target;

      if (input.files && input.files[0]) {
        var reader = new FileReader();

        // Load a preview of the image and append to the container
        reader.onload = function (e) {
          App.PhotoPreview.set(element, e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
      }
    });
  },
  set: function(element, imgSrc) {
    var img = $("<img>").attr('src', imgSrc).addClass("img-thumbnail photo-preview");
    $(element).html(img);
    App.PhotoPreview.autoOrient(img.get(0));
  },
  autoOrient: function(image) {
    // Get the EXIF data from the image
    EXIF.getData(image, function() {
      var orientation = EXIF.getTag(this, "Orientation");

      // Rotate the image to ensure it appears right side up
      switch (orientation) {
        case 6:
          $(image).css('transform', 'rotate(90deg)');
          break;
        case 8:
          $(image).css('transform', 'rotate(270deg)');
          break;
        case 3:
          $(image).css('transform', 'rotate(180deg)');
          break;
      }
    });
  }
}

$(document).on("turbolinks:load", function() {
  $("[data-behavior=person-photo-preview]").each(function(index, element) {
    App.PhotoPreview.init(element);
  });
  $("[data-behavior=guardian-photo-preview]").each(function(index, element) {
    App.PhotoPreview.init(element);
  });
  $("[data-behavior=take-person-photo]").click(function(e) {
    $("[data-ujs-target=person-photo-input]").trigger("click");
  });
  $("[data-behavior=take-guardian-photo]").click(function(e) {
    $("[data-ujs-target=guardian-photo-input]").trigger("click");
  });
});
