<template>
  <reco-modal 
    v-on:backButtonClicked="backButtonClicked" 
    v-on:doneButtonClicked="doneButtonClicked" 
    :withBackButton="withBackButton" 
    :withDoneButton="false"
    :withCloseButton="true"
    :withCloseConfirmation="true"
    v-on:closeButtonClicked="onCloseButtonClicked"
    :title="title">

    <ion-content slot="content">
      <ion-list lines="none">   

        <ion-item lines="full" style="height: 0px !important; margin-top: 10px;" />

        <reco-post 
          ref="post" :post="post" :isPreview="true" 
          v-on:deleteImage="onDeleteImage($event)"
          v-on:addImage="chooseSource()"
          :excludedFeatures="excludedFeatures.includes('theme') ? ['border'] : []"
        />

        <ion-item lines="full" style="height: 0px !important; margin-top: 10px;" />

        <ion-card 
          v-if="!excludedFeatures.includes('theme')"
          class="loc-full-width-card" 
          style="padding-bottom: 10px"
        >
          <ion-item lines="none">
            <ion-label class="loc-label" slot="start" style="font-weight: 600; position: relative; top: 4px; left: -8px">Theme (optional)</ion-label>
          </ion-item>
          <div class="color-container">
            <div 
              class="color-box" 
              v-for="color in colors"
              :key="color"
              :style="{ background: color }"
              @click="setColor(color)">
              <ion-icon class="mood-checkmark" name="checkmark" v-if="post.category.color === color"></ion-icon> 
              <span class="mood-text">{{ colorToText(color) }}</span>
            </div>
          </div>
        </ion-card>

      </ion-list>
        
      <ion-item lines="full" style="height: 0px !important; margin-top: 10px;" />

      <ion-card class="loc-full-width-card photo-publish-btns" >
        <ion-item lines="none">
          <div style="width: 100%; overflow: hidden; margin-top: 10px; margin-bottom: 7px; ">
            <div 
              class="add-photo-button"
              :style="`border: 2px solid ${color}; color: ${color}`"
              @click="chooseSource()" 
            >
              <!-- v-if="!post.images || !post.images.length" -->
              <ion-icon name="camera"></ion-icon>  
            </div>

            <span class="add-photo-button-text"
            :style="`color: ${color}`"
            @click="chooseSource()" 
            >ADD</span>   

            <input type="file" ref="fileInput" style="display: none" accept="image/*" @change="onFilePickedFromComputer($event)" />
            
              <div v-if="isEdit"
              class="publish-button" 
              :style="`border: 1px solid ${color}; background: ${color}`"
              @click="doneButtonClicked"
            >
              Submit Edit
            </div>
            <div v-else
              class="publish-button" 
              :style="`border: 1px solid ${color}; background: ${color}`"
              @click="doneButtonClicked"
            >
              Post
            </div>
          </div>
        </ion-item>
      </ion-card>
    </ion-content>
  </reco-modal>
</template>

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

export default {
  components: { RecoModal, RecoPost },
  props: {
    title: {
      type: String,
      default: "Post Preview"
    },
    post: {
      type: Object,
    },
    backButtonClicked: {
      type: Function,
      default: () => { return }
    },
    doneButtonClicked: {
      type: Function,
      default: () => { return }
    },
    withBackButton: {
      type: Boolean,
      default: true,
    },
    withDoneButton: {
      type: Boolean,
      default: false,
    },
    colors: {
      type: Array,
      default: () => ([
        '#c42b3d', '#e8a600', '#3a86ff', '#8338ec', '#02c39a', '#577590'
      ])
    },
    excludedFeatures: {
      type: Array,
      default() {
        return [];
      },
    },
    color: {
      type: String,
    },
    previewCloseButtonClicked:{
      type: Function,
      default: () => { return }
    }
  },
  watch: {
    images(val) {
      console.log('images val ', val);
      if(val && val.length) {
        setTimeout(() => {
          this.$refs.post.updateSlider();
        }, 300);
        setTimeout(() => {
          this.$refs.post.slideToEnd();
        }, 600);
        console.log('Images are updated.');
      }
    }
  },
  data() {
    return {
      images: [],
      imageURLs: [],
      imageDimensions: [],
      isEdit: false
    }
  },
  methods: {

    parseTags(oldTags) {
      let tags = [];
      for (var i = 0; i < oldTags.length; i++) {
        oldTags[i].matching = false;
        tags.push(oldTags[i])
      }
      return tags;
    },

    chooseSource() {
      // if on mobile
      if (navigator.camera) {

        return this.$ionic.alertController
        .create({
          header: 'Choose source',
          buttons: [
            {
              text: 'Add from library',
              handler: () => {
                this.onPickFile(navigator.camera.PictureSourceType.PHOTOLIBRARY)
              },
            },
            {
              text: 'Take new photo',
              cssClass: 'take-new-photo-button',
              handler: () => {
                this.onPickFile(navigator.camera.PictureSourceType.CAMERA)
              },
            },
          ],
        })
        .then(a => a.present());

      // if on computer
      } else {
        this.onPickFile();
      }
    },

    onCloseButtonClicked(){
      this.previewCloseButtonClicked();
    },

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

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

    /*** PARSE MOBILE IMAGE ***/
    parseMobileImage(path) {
      this.openRecoImageCropModal(path);
    },

    /*** PARSE COMPUTER IMAGE ***/
    onFilePickedFromComputer(event) {
      let file = event.target.files[0];
      let fileName = file.name;
      this.isLoaded = false;
 
      // load image and compress it
      const reader = new FileReader();
      reader.readAsDataURL(file);

      // load image
      reader.onload = event => {
        this.openRecoImageCropModal(event.target.result);
      };
      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', async () => {
        console.log('file', file);
        // update images
        this.images.push(file);
        console.log('images: ', this.images);

        this.imageURLs.push(fileReader.result);
        console.log('imageURLs: ', this.imageURLs);

        this.imageDimensions.push({width: width, height: height});
        console.log('images_dimensions: ', this.imageDimensions);

        this.setImages(this.images, this.imageURLs, this.imageDimensions);

      });
    },

    onDeleteImage(index) {
      this.isLoaded = false;
      this.images.splice(index, 1);
      console.log('images del: ', this.images);
      this.imageDimensions.splice(index, 1);
      console.log('images_dimensions del: ', this.imageDimensions);
      this.imageURLs.splice(index, 1);
      console.log('imageURLs del: ', this.imageURLs);
      this.setImages(this.images, this.imageURLs, this.imageDimensions);
    },

    colorToText(color) {
      const colorTextMap = {};
      colorTextMap['#c42b3d'] = 'S.O.S.';
      colorTextMap['#e8a600'] = 'Free Time';
      colorTextMap['#3a86ff'] = 'Business';
      colorTextMap['#8338ec'] = 'Sharing';
      colorTextMap['#02c39a'] = 'Environment';
      colorTextMap['#577590'] = 'Information';
      return colorTextMap[color];
    },
    openRecoImageCropModal(image) {
      const self = this;
      return self.$ionic.modalController.create({
        component: RecoImageCrop,
        componentProps: {
          propsData: {    
            image: image
          },
          methods: {  
            closeImageCrop(cropResult){
              if(cropResult){
                self.updateImages(cropResult, 600, 600);
              }            
              self.recoImageCrop.dismiss();
            }         
          },
        },
      })
      .then(c => {
        self.recoImageCrop = c;
        self.recoImageCrop.present();
      })
    }
  },
}
</script>

<style scoped lang="css">
  .loc-item {
    font-size: 16px;
  }
  .intro {
    font-size: 17px;
    line-height: 28px;
  }
  .loc-label {
    padding: 8px 0;
  }
  .loc-divider {
    line-height: 7px !important;
    padding: 0px;
    min-height: 12px;
    border-top: 0px solid #ccc;
    border-bottom: 1px solid #ccc;
    background-color: #fff;
  }
  .add-photo-button {
    float: left;
    width: 40px;
    line-height: 36px;
    font-weight: bold;
    font-size: 21px;
    border-radius: 20px;
    background: #fff;
    text-align: center;
  }
  .add-photo-button:active {
    position: relative;
    top: 2px;
  }
  .add-photo-button ion-icon {
    position: relative;
    top: 3px;
  }
  .add-photo-button-text{
    float:left;
    font-size: 18px;
    font-weight: bold;
    padding-top: 10px;
    margin-left: 3px;
  }
  .publish-button {
    float: right;
    width: 120px;
    color: #fff;
    line-height: 36px;
    font-weight: bold;
    font-size: 16px;
    border-radius: 10px;
    text-align: center;
  }
  .publish-post {
    margin: 15px;
    width: 100%;
    color: #fff;
    line-height: 36px;
    font-weight: bold;
    font-size: 16px;
    border-radius: 10px;
    text-align: center;
  }
  .publish-post:active {
    position: relative;
    top: 2px;
  }
  .loc-label {
    padding: 8px 0;
  }
  .loc-full-width-card {
    position: relative;
    margin: 0;
    border-radius: 0px;
    -webkit-box-shadow: 0px 0 10px rgba(0,0,0,0.2);
    box-shadow: 0px 0 10px rgba(0,0,0,0.2);
  }
  .color-container {
    display: flex;
    flex-wrap: wrap;
    padding-top: 6px;
    padding-left: 6px;
  }
  .color-box {
    margin-right: 6px;
    margin-bottom: 6px;
    width: calc(33.3% - 6px);
    height: 34px;
    line-height: 34px;
    font-size: 14px;
    text-align: center;
    border-radius: 4px;
    color: #fff;
  }
  .mood-checkmark {
    font-size: 22px;
    position: relative;
    top: 6px;
  }
  .loc-full-width-card.photo-publish-btns{
    position: fixed;
  	right: 0px;
  	bottom: 0px;
  	left: 0px; 
  }
</style>

<style lang="css">
.take-new-photo-button {
    font-weight: 400 !important;
}
</style>