<template>
  <div class="chat--picker">
    <a 
    class="chat--picker-document"
    @click="pickDocument()"> Document </a>
    <input 
      ref="filepicker"
      type="file" 
      accept="image/*" 
      style="display:none" 
      v-on:change="handleFiles()">
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';

import MessageText from './MessageText.vue';
import MessageAudio from './MessageAudio.vue';
import MessageImage from './MessageImage.vue';
import MessageDocument from './MessageDocument.vue';
import { getFileCategory, MESSAGE_TYPE, InputMessage, Attachment } from './type';


@Component({
  components: {
    MessageText,
    MessageAudio,
    MessageImage,
    MessageDocument,
  },
})
export default class InputFilePicker extends Vue {
  private pickDocument() {
    console.log('document');
    this.pick('.txt,.pdf,.doc,docx,image/*');
  }

  private cancel() {
    console.log('camera');

    this.$emit('complete');
  }

  /**
   * Open the filepicker with the given
   * accept type set.
   */
  private pick(accept: string) {
    const filepicker = (this.$refs.filepicker as HTMLInputElement);
    filepicker.accept = accept;
    filepicker.click();
  }

  private handleFiles() {
    const filepicker = (this.$refs.filepicker as HTMLInputElement);
    console.log('result');
    console.log( filepicker.files!.length );


    if (filepicker.files && filepicker.files.length > 0) {
      const file = filepicker.files[0];
      // console.log(file.lastModified);
      // console.log(file.name);
      // console.log(file.size);
      // console.log(file.type);

      this.sendFileMessage(file);
    }
    this.$emit('complete');
  }

  private sendFileMessage(file: File) {
    const messageType = getFileCategory(file.type);
    console.log(file.type, '=>', messageType);

    if (messageType) {
      if (messageType === MESSAGE_TYPE.image) {
        const attachment = Attachment.fromBlob(file, file.type, file.name, true);
        const message = InputMessage.newImageMessage('', attachment);
        this.$emit('message', message);
      }
      if (messageType === MESSAGE_TYPE.document) {
        const attachment = Attachment.fromBlob(file, file.type, file.name,  false);
        const message = InputMessage.newDocumentMessage(file.name, attachment);
        this.$emit('message', message);
      }
    } else {
      // TODO: better popup message
      alert('Unsupported file type:' + file.type);
    }

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">

</style>
