<template>
  <div>
    <!-- <object3d ref="block3d" name="Content" :position="position"> -->
    <!-- <mesh ref="block3d" name="ContentBlock" :position="position">
      <geometry type="Box" :args="[size.x, size.y, size.z]" />
      <material type="MeshLambert" :color="color" :options="opts" />
    </mesh> -->
    <mesh
      v-if="label_canvas"
      ref="label3d"
      name="Content"
      :position="label_position"
      :rotation="{
        x:deg2rad(rotation.x),
        y:deg2rad(rotation.y),
        z:deg2rad(rotation.z)
      }"
    >
      <geometry type="Plane" :args="[label_size.width, label_size.height]" />
      <material type="MeshLambert" :options="label_opts">
        <texture :options="label_texture_opts" />
      </material>
    </mesh>
    <mesh
      v-if="img_canvas"
      ref="img3d"
      name="Content"
      :position="img_position"
      :rotation="{
        x:deg2rad(rotation.x),
        y:deg2rad(rotation.y),
        z:deg2rad(rotation.z)
      }"
    >
      <geometry type="Plane" :args="[img_size.width, img_size.height]" />
      <material type="MeshLambert" :options="img_opts">
        <texture :options="img_texture_opts" />
      </material>
    </mesh>
  <!-- </object3d> -->
  </div>
</template>

<script>
import { mapInstanceState, mapInstanceMutations } from '@urbn/vuex-helpers'
// import { mapState, mapGetters } from 'vuex'

// import { VIMEO } from 'api/vimeo-axios'
// import qs from 'querystring'

import * as THREE from 'three'
import mixins from 'components/mixins'

// We'll determine our module based on the moduleName prop on this component
// https://www.npmjs.com/package/@urbn/vuex-helpers
const getModuleName = cmp => `project:${cmp.prtId}`

export default {
  name: 'ContentBlock',
  mixins: [mixins],
  props: { prtId: Number, type: String, data: Object },
  data: () => ({
    // block3d: null,
    project: null,
    size: { width: 0, height: 0 },
    position: { x: 0, y: 0, z: 0 },
    rotation: { x: 0, y: 0, z: 0 },
    // opts: {
    //   side: THREE.DoubleSide
    //   // wireframe: false,
    //   // transparent: false,
    //   // opacity: 0.6
    // },
    isOpened: false,
    label_canvas: null,
    label_position: { x: 0, y: 0, z: 0 },
    label_size: null,
    label_opts: {
      // side: THREE.DoubleSide,
      // wireframe: false,
      transparent: true
      // opacity: 0.6
      // renderOrder: 0
    },
    preview_img_url: null,
    img_canvas: null,
    img_size: { x: 0, y: 0 },
    img_position: { x: 0, y: 0, z: 0 },
    img_opts: {
      // side: THREE.DoubleSide,
      // wireframe: false,
      // transparent: true
      // opacity: 0.6
      // renderOrder: 0
    },
    img_padding: 0.25,
    face: null
  }),
  computed: {
    ...mapInstanceState(getModuleName, {
      projSize: state => state.size,
      projPos: state => state.position,
      projWall: state => state.wall,
      gridsContentPlaced: state => state.gridsContentPlaced,
      contents_size_factor: state => state.contents_size_factor,
      faces_opaques: state => state.Faces_opaques,
      gridCel: state => state.gridCel
    }),
    color () {
      let color = 0x000000
      return color
    },
    label_texture_opts () {
      return {
        canvas: this.label_canvas,
        minFilter: THREE.LinearFilter,
        wrapS: THREE.ClampToEdgeWrapping,
        wrapT: THREE.ClampToEdgeWrapping
      }
    },
    img_texture_opts () {
      return {
        canvas: this.img_canvas,
        minFilter: THREE.LinearFilter,
        wrapS: THREE.ClampToEdgeWrapping,
        wrapT: THREE.ClampToEdgeWrapping
      }
    },
    id () {
      return this.data.id
    }
  },
  created () {
    this.size.width = this.gridCel.width
    this.size.height = this.gridCel.height

    if (typeof this.data.country !== 'undefined' &&
      typeof this.data.country.id !== 'undefined') {
      // console.log('this.data.country.id', parseInt(this.data.country.id))
      switch (parseInt(this.data.country.id)) {
        case 1:
          this.face = 'back'
          break
        case 2:
          this.face = 'right'
          break
        case 3:
          this.face = 'left'
          break
      }
    } else {
      let face = Math.random()
      switch (this.faces_opaques) {
        case 1:
          this.face = 'back'
          break
        case 2:
          // RANDOMLY USE 2 FACES
          if (face < 0.5) {
            this.face = 'left'
          } else {
            this.face = 'right'
          }
          break
        case 3:
          // RANDOMLY USE 3 FACES
          if (face < 0.33) {
            this.face = 'left'
          } else if (face >= 0.33 && face < 0.66) {
            this.face = 'back'
          } else {
            this.face = 'right'
          }
          break
        case 4:
          // RANDOMLY USE 4 FACES
          if (face < 0.25) {
            this.face = 'left'
          } else if (face >= 0.25 && face < 0.5) {
            this.face = 'back'
          } else if (face >= 0.5 && face < 0.75) {
            this.face = 'right'
          } else {
            this.face = 'front'
          }
          break
      }
    }
    // this.face = 'left'
    // console.log('face', this.face)
    // define side
    let side
    switch (this.face) {
      case 'back':
      case 'front':
        side = 'x'
        break
      case 'left':
      case 'right':
        side = 'z'
        break
    }
    // Get GRID's CEL
    if (typeof this.gridsContentPlaced[side] === 'undefined' ||
      typeof this.gridsContentPlaced[side][this.face] === 'undefined' ||
      typeof this.gridsContentPlaced[side][this.face][this.type] === 'undefined' ||
      typeof this.gridsContentPlaced[side][this.face][this.type][this.id] === 'undefined') {
      // First shift grid place (will transfer it from free places to occupied places)
      this.shiftGrid({ face: this.face, type: this.type, id: this.id })
    }
    // rotation and position
    // console.log(`side: ${side}, face: ${this.face}, type: ${this.type}, id: ${this.id}`)
    let gridPos = this.gridsContentPlaced[side][this.face][this.type][this.id]
    // console.log('gridPos', gridPos)
    this.position.x = gridPos.x
    this.position.z = gridPos.z
    this.position.y = gridPos.y
    this.rotation.y = gridPos.ry

    if (this.data.Vimeo) {
      this.preview_img_url = this.data.Vimeo.thumbnail_url_with_play_button
    } else if (this.data.Media && this.data.Media.length) {
      this.preview_img_url = `https://api.anarchive-muntadas.figli.io${this.data.Media[0].url}`
    } else if (this.data.Images && this.data.Images.length) {
      this.preview_img_url = `https://api.anarchive-muntadas.figli.io${this.data.Images[0].url}`
    }

    if (this.preview_img_url) {
      // console.log(this.preview_img_url)
      // create image object with a promise (async img loading)
      this.createImgCanvas(this.preview_img_url)
        .then(({ img, canvas }) => {
          // console.log('THEN img loaded ok', this, img, canvas)
          // canvas is way bigger than displayable for good resolution
          // reduce it keeping good resolution
          // and fit the width and height to the screen
          let f
          if (canvas.width >= canvas.height) {
            f = this.size.width / canvas.width
            this.img_size.width = canvas.width * f - this.img_padding * 2
            this.img_size.height = canvas.height * f - this.img_padding * 2
          } else {
            f = this.size.height / canvas.height
            this.img_size.height = canvas.height * f - this.img_padding * 2
            this.img_size.width = canvas.width * f - this.img_padding * 2
          }
          // console.log(`size.x :${this.size.width}, size.y :${this.size.height}, canvas.width: ${canvas.width}, canvas.height: ${canvas.height}, f: ${f}, img_size.width: ${this.img_size.width}, img_size.height: ${this.img_size.height}`)

          this.img_position.y = this.position.y
          switch (side) {
            case 'z':
              this.img_position.z = this.position.z + this.size.width / 2
              this.img_position.x = this.position.x
              break
            case 'x':
              this.img_position.x = this.position.x + this.size.width / 2
              this.img_position.z = this.position.z
              break
          }
          this.img_canvas = canvas
          this.curObj.needsUpdate()
        })
        .catch(function () {
          console.warn('CATCH img load ERROR')
        })
    }
    // else {
    //   // if no images, display title
    //   let labelCanvas = this.createLabelCanvas(this.data.Name, 48, 21, 0x000000)
    //   // console.log('this.label_canvas', this.label_canvas)
    //   let f
    //   if (labelCanvas.width >= labelCanvas.height) {
    //     f = this.size.width / labelCanvas.width
    //     this.label_size.width = labelCanvas.width * f
    //     this.label_size.height = labelCanvas.height * f
    //   } else {
    //     f = this.size.height / labelCanvas.height
    //     this.label_size.height = labelCanvas.height * f
    //     this.label_size.width = labelCanvas.width * f
    //   }
    //
    //   this.label_position.y = this.position.y
    //   switch (side) {
    //     case 'z':
    //       this.label_position.z = this.position.z + this.size.width / 2
    //       this.label_position.x = this.position.x
    //       break
    //     case 'x':
    //       this.label_position.x = this.position.x + this.size.width / 2
    //       this.label_position.z = this.position.z
    //       break
    //   }
    //
    //   this.label_canvas = labelCanvas
    // }
  },
  mounted () {
    // this.block3d = this.$refs.block3d.curObj
    // this.block3d.castShadow = true
    // this.block3d.receiveShadow = true
  },
  updated () {
    if (!this.curObj && this.$refs.img3d) {
      this.curObj = this.$refs.img3d.curObj
      // record self references
      this.curObj.userData = {
        vnode: this
      }
    }
  },
  methods: {
    ...mapInstanceMutations(getModuleName, {
      shiftGrid: 'shiftGrid'
    }),
    open () {
      this.isOpened = true
      // this.loadContents()
    }
  }
}
</script>
