<template>
    <reco-modal 
      v-on:backButtonClicked="backButtonClicked" 
      :withBackButton="true" 
      :withDoneButton="true"
      :doneButtonText="'Send'" 
      v-on:doneButtonClicked="sendFeedback" 
      :title="'Contact Actiways'">

      <ion-content slot="content">

        <!-- Type select -->
        <ion-item class="loc-item" lines="none">
          <ion-label class="loc-label" style="padding-bottom: 0px">Hey Actiways!</ion-label>
        </ion-item>      

        <ion-radio-group 
          :value="type">
          <ion-item>
            <ion-label>I would like to report a bug!</ion-label>
            <ion-radio class="loc-radio" slot="start" :value="'bugreport'" v-on:ionSelect="event => type = event.target.value"></ion-radio>
          </ion-item>

          <ion-item>
            <ion-label>I would like to submit feedback!</ion-label>
            <ion-radio class="loc-radio" slot="start" :value="'feedback'" v-on:ionSelect="event => type = event.target.value"></ion-radio>
          </ion-item>

          <ion-item>
            <ion-label>Delete my account.</ion-label>
            <ion-radio class="loc-radio" slot="start" :value="'delete_account'" v-on:ionSelect="event => type = event.target.value"></ion-radio>
          </ion-item>
        </ion-radio-group>

        <!-- 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">{{subject.length}}</span><span class="max-chars">/30</span>
          </div>
        </ion-item>
        <ion-item class="loc-item">
          <ion-input ref="mottoInput"
          class="loc-input"
            placeholder="Type your subject here..." 
            :maxlength="30"
            inputmode="text"
            v-on:ionInput="event => subject = event.target.value"
            :value="subject"
          />
        </ion-item>

        <!-- Description -->
        <ion-item class="loc-item" lines="none">
          <ion-label class="loc-label" style="padding-bottom: 0px">Message</ion-label>
        </ion-item>
        <ion-item class="loc-item">
          <ion-textarea 
            ref="descriptionInput" 
            class="loc-input"
            placeholder="Type your message here..." 
            :rows="6" 
            inputmode="text"
            v-on:ionInput="event => message = event.target.value"
            :value="message"
          />
          <!-- <reco-text-editor :textChanged="onTextChanged"/> -->
        </ion-item>

        <!-- Screenshot -->
        <ion-item lines="none">
          <div v-if="screenshot === null" class="screenshot-placeholder">
            <b-icon class="no-screenshot" icon="file-earmark-minus"></b-icon>
            <span class="loc-placeholder-text">You have no screenshot attached.</span>
          </div>	
          
          <div v-else class="screenshot-placeholder">
            <b-icon class="yes-screenshot" icon="file-earmark-check"></b-icon>
            <span class="loc-placeholder-text">Screenshot attached.</span>
          </div>
        </ion-item>

        <ion-item lines="none">
          <input type="file" ref="fileInput" style="display: none" accept="image/*" @change="onFilePickedFromComputer($event)" />
          <div v-if="screenshot === null" class="loc-upload-screenshot-btn" @click="chooseSource()">Upload Screenshot</div>
          <div v-else class="loc-upload-screenshot-btn" @click="onDeleteImage()">Delete Screenshot</div>
        </ion-item>

    </ion-content>

    </reco-modal>
</template>
<script>
import RecoModal from '@/components/complex/RecoModal.vue';

export default {
    data(){
        return {
            subject: "",
            message: "",
            screenshot: null,
            type: "bugreport"
        }
    },
    components: {
      RecoModal
    },
    props:{
      backButtonClicked: {
        type: Function,
        default: () => { return }
      },
      doneButtonClicked: {
        type: Function,
        default: () => { return }
      }
    },
    methods:{
    chooseSource() {
      // if on mobile
      if (navigator.camera) {        
        this.onPickFile(navigator.camera.PictureSourceType.PHOTOLIBRARY)
      // 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);
        }, {
          sourceType: source,
        });

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

    /*** PARSE MOBILE IMAGE ***/
    parseMobileImage(path) {
      this.isLoaded = false;
      let imgName = path.split("/").pop();

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

      // set canvas
      img.onload = () => {
        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()
          });

          // 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) {
      let file = event.target.files[0];
      let fileName = file.name;
      this.isLoaded = false;

      // 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()
            });
            
            // 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', () => {    
        this.screenshot = file;
      });
    },
    onDeleteImage() {
      this.screenshot = null;
    },
    sendFeedback(){
      if(this.subject.length < 3 || this.message.length < 3 ){
        return this.$ionic.alertController
        .create({
          header: 'More information needed!',   
          message: 'The subject or the message is too short!',      
          buttons: [
            {
              text: 'Ok',
              role: 'cancel',
            }          
          ]
        })
        .then(a => a.present());       
      }
      const payload = {
        subject: this.subject,
        message: this.message,
        screenshot: this.screenshot,
        type: this.type
      };
      this.doneButtonClicked(payload);
    },
  }
}
</script>
<style>
  .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;
  }
  .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-select{
    display: block;
  }
  .loc-radio{
    --color-checked: var(--actiways-primary-color);
  }
  .loc-upload-screenshot-btn{
	  margin: 10px;
    color: #fff;
    width: 93%;
    line-height: 32px;
    font-weight: bold;
    font-size: 15px;
    border-radius: 10px;
    background: var(--actiways-primary-color);
    text-align: center;
  }
  .loc-upload-screenshot-btn:active {
    position: relative;
    top: 2px;
    background: var(--actiways-primary-color);
  }
  .no-screenshot{
    color: red;
    margin-right: 10px;
    font-size: 20px;
  }
  .yes-screenshot{
    color: green;
    margin-right: 10px;
    font-size: 20px;
  }
  .loc-placeholder-text{
    color: #7f8c8d !important;
    font-weight: 500 !important;
  }
  .screenshot-placeholder{
    margin: 0 auto;
  }
</style>