<template>
  <div>
    <div><video ref="video" id="video" width="640" height="480" autoplay></video></div>
    <div class="mt-2">
      <button class="button is-primary" id="snap" v-on:click="capture()">Chụp ảnh</button>
      <a class="ml-6" @click="switchView()">
        <SvgIcon v-bind="{name: 'camera_switch.svg', type: 'black', size: 40}"></SvgIcon>
      </a>
    </div>
    <canvas v-show="false" ref="canvas" id="canvas" width="640" height="480"></canvas>
  </div>
</template>
<script>
  export default {
    data: function() {
      return {
        video: {},
        canvas: {},
        current: 'front'
      }
    },
    mounted: function() {
      this.openCamera()
    },
    beforeDestroy() {
      var vidTrack = this.video.srcObject.getVideoTracks()
      vidTrack.forEach(track => {
        track.stop()
        track.enabled = false
      })
    },
    methods: {
      openCamera() {
        let f = this.current==='front'? {facingMode: "user"} : {facingMode: {exact: "environment"}}
        this.video = this.$refs.video;
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
          navigator.mediaDevices.getUserMedia({ video: f, audio: false }).then(stream => {
            video.srcObject = stream;
            this.video.play();
          });
        }
      },
      capture() {
        this.canvas = this.$refs.canvas;
        let scale = 600 / this.video.videoWidth;
        let w = this.video.videoWidth * scale;
        let h = this.video.videoHeight * scale;
        this.canvas.width = w;
        this.canvas.height = h;
        var context = this.canvas
          .getContext("2d")
          .drawImage(this.video,0,0,w,h);
        this.canvas.toBlob(blod=>this.saveAs(blod))
      },
      async saveAs(blod) {
        var form = new FormData();
        let name = `${this.$id()}.png`
        this.fileName = `${this.$dayjs(new Date()).format("YYYYMMDDhhmmss")}-${name}` 
        form.append('filename', this.fileName)
        form.append('name', name)
        form.append('file', blod)
        form.append('type', 'image')
        form.append('size', 100)
        form.append('user', this.$store.state.login.id)
        let result = await this.$insertapi('upload', form)
        if(result==='error') return
        let row = result.rows[0]
        const file = new File([blod], name, {type: "image/png"})
        row.source = {file: file}
        this.$emit('modalevent', {name: 'selectimage', data: row})
        this.$emit('close')
      },
      switchView() {
        this.current = this.current==='front'? 'back' : 'front'
        var vidTrack = this.video.srcObject.getVideoTracks()
        vidTrack.forEach(track => {
          track.stop()
          track.enabled = false
        })
        this.openCamera()
      }
    }
  }
</script>