<template>
  <reco-modal 
    v-on:backButtonClicked="backButtonClicked" 
    v-on:doneButtonClicked="doneButtonClicked" 
    :withBackButton="withBackButton" 
    :withDoneButton="withDoneButton"
    :title="title">

    <ion-content slot="content">
      <div v-if="!isLoaded" style="height: 400px; background: #2f3640"></div>
      <ion-slides 
        v-if="isLoaded"
        pager="true" 
        ref="ionSlider"
        :options="sliderOpts" 
        class="loc-slides" 
        style="height: 400px; background: #2f3640"
        v-on:ionSlideTap="slideTapped($event)">
        <ion-slide v-for="(image, index) in imageURLs" :key="'key_'+index" style="height: 300px">
          <img :src="image" />
        </ion-slide>
      </ion-slides>
      <ion-button @click="onPickFile()">Add Image</ion-button>
      <ion-button v-if="imageURLs.length" color="danger" @click="deleteImage()">Delete Image</ion-button>
      <input type="file" ref="fileInput" style="display: none" accept="image/*" @change="onFilePickedFromComputer($event)" />
    </ion-content>

  </reco-modal>
</template>

<script>
import RecoModal from '@/components/complex/RecoModal.vue';

export default {
  components: { RecoModal },
  props: {
  	title: {
  		type: String,
  		default: "Image Editor"
  	},
    backButtonClicked: {
      type: Function,
      default: () => { return }
    },
    doneButtonClicked: {
      type: Function,
      default: () => { return }
    },
    withBackButton: {
      type: Boolean,
      default: true,
    },
    withDoneButton: {
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      images: [],
      imageURLs: [],
      imageDimensions: [],
      isLoaded: false,
      sliderOpts: {
        zoom: {
          maxRatio: 3,
          toggle: true,
        },
        initialSlide: 1, 
        speed: 400,
      },
    }
  },
  methods: {


    /*** ON PICK FILE ***/
    onPickFile() {
      // if on mobile
      if (navigator.camera) {
        navigator.camera.getPicture(path => {
          path = window.Ionic.WebView.convertFileSrc(path);
          console.log("New path: ", path);
          this.parseMobileImage(path);
        }, error => {
          console.log("Error with camera plugin: ", error);
        }, {
          sourceType: navigator.camera.PictureSourceType.SAVEDPHOTOALBUM,
        });

      // if on computer
      } else {
        this.$refs.fileInput.click();
        this.$refs.fileInput.click();
      }    
    },


    /*** PARSE MOBILE IMAGE ***/
    parseMobileImage(path) {
      console.log("Hello World! 1");
      this.isLoaded = false;
      console.log("Path: ", path);
      let imgName = path.split("/").pop();
      console.log("Image name: ", imgName);

      // set image
      let img = new Image(600, 600);

      // set canvas
      img.onload = () => {
        console.log("Image is loaded.");
        let canvas = document.createElement('canvas');
        canvas.width = 600;
        canvas.height = 600;
        let ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, 600, 600);

        // convert canvas to blob
        ctx.canvas.toBlob((blob) => {

          // get file
          const file = new File([blob], imgName, {
            type: 'image/jpeg',
            lastModified: Date.now()
          });
          console.log("File: ", file);

          // make readable image
          this.updateImages(file, 600, 600);  
        }, 'image/jpeg', 1);
      };

      img.onerror = (error) => {
        console.log("Image Load Failed");
        console.log(JSON.stringify(error));
      };

      // set src
      img.src = path;
    },


    /*** PARSE COMPUTER IMAGE ***/
    onFilePickedFromComputer(event) {
      console.log("Hello World! 2");
      let file = event.target.files[0];
      let fileName = file.name;
      this.isLoaded = false;
      console.log("File: ", file);

      // load image and compress it
      const edge = 560;
      const reader = new FileReader();
      reader.readAsDataURL(file);

      // load image
      reader.onload = event => {
        const img = new Image();
        img.src = event.target.result;

        // load newly created image
        img.onload = () => {
          // set dimensions
          const width = img.width > img.height ? edge : (edge / img.height) * img.width;
          const height = img.width > img.height ? (edge / img.width) * img.height : edge;
          
          // set canvas
          let canvas = document.createElement('canvas');
          canvas.width = width;
          canvas.height = height;
          let ctx = canvas.getContext('2d');
          ctx.drawImage(img, 0, 0, width, height);

          // convert canvas to blob
          ctx.canvas.toBlob((blob) => {

            // get file
            file = new File([blob], fileName, {
              type: 'image/jpeg',
              lastModified: Date.now()
            });
            console.log("File: ", file);
            
            // make readable image
            this.updateImages(file, width, height);
            
          }, 'image/jpeg', 1);
        }

        img.onerror = (error) => {
          console.log("Image Load Failed");
          console.log(JSON.stringify(error));
        };
      };
      reader.onerror = error => console.log("Error reading image: ", error);
    },


    /*** MAKE READABLE FROM IMAGE ***/
    updateImages(file, width, height) {
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.addEventListener('load', () => {
        
        // update images
        this.images.push(file);
        this.imageURLs.push(fileReader.result);
        this.imageDimensions.push({width: width, height: height});
        this.setImages(this.images, this.imageURLs, this.imageDimensions);
        console.log("UPDATED");

        // update gallery
        setTimeout(() => {
          this.isLoaded = true;
          setTimeout(() => this.$refs.ionSlider.slideTo(this.images.length), 300);
        }, 500);

      });
    },


    /*** ZOOM ON TAP ***/
    slideTapped($event) {
      $event.target.swiper.zoom.toggle();
    },


    /*** ON DELETE IMAGE ***/
    deleteImage() {
      this.$refs.ionSlider.getActiveIndex().then(index => {
        this.onDeleteImage(index);
      });
    },
    onDeleteImage(index) {
      this.isLoaded = false;
      this.images.splice(index, 1);
      this.imageDimensions.splice(index, 1);
      this.imageURLs.splice(index, 1);
      this.setImages(this.images, this.imageURLs, this.imageDimensions);
      setTimeout(() => (this.isLoaded = true), 300);
      setTimeout(() => this.$refs.ionSlider.slideTo(this.images.length), 600);
    },
  }
}
</script>