<template>
    <reco-modal 
        v-on:backButtonClicked="backButtonClicked" 
        :withBackButton="true" 
        :withDoneButton="false"
        :title="'On the Spot'">
    <ion-content slot="content" ref="content">


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

        <!-- post gallery -->
        <ion-card class="loc-full-width-card" >
          <input type="file" ref="fileInput" style="display: none" accept="image/*" @change="onFilePickedFromComputer($event)" />
          <div>
            <img :src="locImage"/>
          </div>        
        

          <!-- Subject -->
          <ion-item class="loc-item" lines="none">
            <ion-label class="loc-label" style="padding-bottom: 0px">Subject</ion-label>
            <div class="char-counter">
              <span class="chars">{{locMotto.length}}</span><span class="max-chars">/30</span>
            </div>
          </ion-item>
          <ion-item class="loc-item" lines="none">
            <ion-input ref="mottoInput"
              class="loc-input"
              placeholder="Type your post subject here..." 
              :maxlength="30"
              inputmode="text"
              v-on:ionInput="event => locMotto = event.target.value"
              :value="locMotto"
              v-on:ionFocus="scrollToBottom()"
            />
          </ion-item>

          <!-- Write Description -->
          <ion-item class="loc-item" lines="none">
            <ion-label class="loc-label" style="padding-bottom: 0px">Description</ion-label>
          </ion-item>
          <ion-item class="loc-item" style="margin-bottom: 20px;">
            <ion-textarea 
              ref="descriptionInput" 
              class="loc-input-textarea"
              placeholder="Type your optional post description here..." 
              :rows="3" 
              inputmode="text"
              v-on:ionInput="event => locDescription = event.target.value"
              :value="locDescription"
              v-on:ionFocus="scrollToBottom()"
            />
            <!-- <reco-text-editor :textChanged="onTextChanged"/> -->
          </ion-item>   
        
          <!-- post language -->
          <ion-item lines="none" class="loc-post-lang-select">
            <ion-label class="loc-label">You are posting in:</ion-label>
            <ion-select 
              :style="{ color }"
              v-on:ionChange="onChangePostLanguage($event)"
              :value="selectedLanguage.shortCode" 
              interface="popover">
              <ion-select-option
                v-for="(language, idx) in languageOptions" 
                :key="idx" 
                :value="language.shortCode">
                {{language.name}}
              </ion-select-option>
            </ion-select>
          </ion-item>   
        </ion-card>
        
        <ion-item lines="none" style="height: 50px !important; margin-top: 10px;" />
      
        <!-- Post buttons -->
        <ion-card class="loc-full-width-card publish-btns">
          <ion-item lines="none" class="loc-btn-container">
               
                <button 
                  :class="locMotto.length < 2 ? 'publish-button globally disabled' : 'publish-button globally'" 
                  @click="submitRapidPost(true)"
                  :disabled="locMotto.length < 2">
                  Post Globally
                </button>               

                <button 
                  :class="locMotto.length < 2 ? 'publish-button locally disabled' : 'publish-button locally'"  
                  @click="submitRapidPost(false)"
                  :disabled="locMotto.length < 2">
                  Post Locally
                </button>
              
          </ion-item>
        </ion-card>
    </ion-content>

    </reco-modal>
</template>

<script>
import RecoModal from '@/components/complex/RecoModal.vue';
import RecoImageCrop from '@/components/complex/RecoImageCrop.vue';
import Languages from '@/assets/languages';
import moment from 'moment';

export default {
    components:{
        RecoModal,
        RecoImageCrop
    },
    props:{       
        backButtonClicked:{
          type: Function,
          default: () => { return; }
        },
        me:{
          type: Object,
          default(){
            return null
          }
        },
        submitPost:{
          type: Function,
          default: () => { return; }
        }
    },
    data(){
        return {
            locMotto: "",
            locDescription: "",
            locImage: "",
            imageDimension: {},
            file: {},  
            color: "#ED1556",
            selectedLanguage: "",
            preSelectedLanguage: "",
            languages: [...Languages],
            languageOptions: [],
            originalWidnowHeight: window.innerHeight
        };
    },
    mounted(){   
      this.chooseSource(); 
      this.setPreSelectedLanguage();  

      window.addEventListener('resize', this.handleResize);
    },
    watch:{  
    },
    methods:{
      handleResize(){
        if(window.innerHeight < this.originalWidnowHeight){
          this.scrollToBottom();
        }
      },
      chooseSource() {
        // if on mobile
        if (navigator.camera) {
            this.onPickFile(navigator.camera.PictureSourceType.CAMERA)
        // if on computer
        } else {
          this.onPickFile();
        }
      },

      /*** 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);
            //if no image selected, dismiss modal
            this.backButtonClicked();
          }, {
            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', () => {
        
        // update image
        this.file = file;
        this.locImage = fileReader.result;
        this.imageDimension = {width: width, height: height};
      });
    },
    openRecoImageCropModal(image) {
      const self = this;
      return self.$ionic.modalController.create({
        component: RecoImageCrop,
        componentProps: {
          propsData: {    
            image: image
          },
          methods: {  
            closeImageCrop(cropResult){
              console.log('crop res', cropResult);
              if(cropResult){
                self.updateImages(cropResult, 600, 600);
              }
              else{
                self.backButtonClicked();                
              }            
              self.recoImageCrop.dismiss();
            }         
          },
        },
      })
      .then(c => {
        self.recoImageCrop = c;
        self.recoImageCrop.present();
      })
    },
    onChangePostLanguage(event){
       this.selectedLanguage = this.languageOptions.find(lang => lang.shortCode === event.target.value);
    },
    setPreSelectedLanguage(){
      this.selectedLanguage = this.preSelectedLanguage ? this.languages.find(lang => lang.shortCode === this.preSelectedLanguage) : this.languages.find(lang => lang.shortCode === this.me.languages.post_language);
      for(const langCode of this.me.languages.spoken_languages){
        let language = this.languages.find(l => l.shortCode === langCode);
        if(language){
          this.languageOptions.push(language);
        }
      }
    },
    submitRapidPost(global){
      const post = this.getPostObject(global);
      this.submitPost(post);
      this.backButtonClicked();
    },
    getPostObject(global){
      let post = {
        settings: {
          type: "direct",
          gender: {display_name: "All", value: "all"},
          age: {lower: "18", upper: "99"},
          expiration: {display_name: "One Day", expires_at: 0, is_expired: false, seconds: 86400, value: "one_day"},
          distance: global ? {display_name: "∞ km", meters: 100000000, value: "infinite"} : {display_name: "1 km", meters: 1000, value: "1_km"},
          max_responses: 12,
          chat_type: {display_name: "single", value: "single"},
          automatic_response: "",
        },
        attributes: {
          gender: this.me.gender,
          birthday: this.me.birthday,
          tags: [{display_name: "On the Spot", is_recommended: true, matching: false, value: "on_the_spot"}],
          category: {color: "#ed1556", display_name: "Other", icon: null, value: "no_category"},
          is_replied: false,
          language: this.selectedLanguage.shortCode,
          bookmarked: [],
          replies: []
        },
        display: {
          user: { 
            uid: this.me.uid, 
            nickname: this.me.nickname, 
            avatar: this.me.avatar,
          },
          type: "direct",
          activity_date_time: this.activityDateTime,
          category: {color: "#ed1556", display_name: "Other", icon: null, value: "no_category"},
          images: [],
          image_dimensions: this.imageDimension,
          tags: {display_name: "On the Spot", is_recommended: true, matching: false, value: "on_the_spot"},
          subject: this.locMotto,
          description: this.locDescription,
          timestamp: Date.now(),
        },
        _meta: {
          location: this.me.location,
          tags: this.tags,
          editId: null
        },
        timestamp: Date.now()
      }
      post.settings.expiration.expires_at = (moment().unix() + post.settings.expiration.seconds) * 1000;
      post.display.images.push(this.file);
      return post;
    },
    scrollToBottom(){
      this.$refs.content.scrollToBottom(500);
    }
  }  
}
</script>

<style scoped lang="css">

.loc-item {
    font-size: 16px;
}
.loc-label {
    padding: 5px 0;
    font-weight: 500;
}
.char-counter {
    color: #636e72;
}
.char-counter .chars {
    font-weight: 600;
    color: #455054;
}
.char-counter .max-chars {
    font-size: 12px;
}
.loc-input {
    --inner-padding-top: 8px;
    --inner-padding-bottom: 8px;
    --placeholder-color: var(--reco-lighter-font-color);
    --placeholder-opacity: 0.66;
}
.loc-input-textarea {
    padding: 8px 0;
}
.loc-slides {
    position: relative;
    z-index: 11;
    border-bottom: 1px solid #ccc;
    width: 100%;
    --bullet-background: var(--actiways-primary-color);
    --bullet-background-active: var(--actiways-primary-color);
}
.add-photo-button {
  float: left;
  margin: 0px 5px 20px 0px;
  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;
}
.publish-button {
  max-width: 140px;
  max-height: 42px;
  line-height: 36px;
  font-weight: bold;
  font-size: 16px;
  border-radius: 10px;
  text-align: center;
  border: 2px solid var(--actiways-primary-color); 
}
.publish-button.locally{
  position: absolute;
  right: 15px;
  background: var(--actiways-primary-color);
  color: #fff;
}
.disabled{
  opacity: 0.5;
}
.publish-button.globally{
  position: absolute;
  background:  #fff;
  color: var(--actiways-primary-color);
}

.loc-full-width-card.publish-btns{
  position: fixed;
  right: 0px;
  bottom: 0px;
  left: 0px;  
  background: #fff;
}
.img-del-button{
	position: absolute;
  top: 10px;
  right: 10px;
 	background-color: var(--actiways-primary-color);
	color: white;
  padding: 3px 6px;
 	border: none;
  cursor: pointer;
  border-radius: 5px;
  text-align: center;
	font-size: 1.5em;
}
.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);
  padding-top: 5px;
  padding-bottom: 5px;
}
.loc-post-lang-select{
  margin-top: -10px;
}
.loc-btn-container{
  margin-top: 5px; 
  margin-bottom: 5px;
}
</style>