<template>
  <div class="l-flex--col o-device-grid-item has-border radius">
    <div class="l-flex__none l-flex--row has-bottom-padding">
      <i class="l-flex__none o-device-grid-item__icon o-icon medium has-bg" />
      <span class="l-flex__fill u-color--info u-ellipsis">截屏</span>
      <i
        v-if="asking"
        class="l-flex__none el-icon-loading u-color--black"
      />
      <i
        v-else
        class="l-flex__none o-icon mini has-bg u-pointer"
        @click="invoke"
      />
    </div>
    <div
      class="l-flex__fill o-preview u-size--contain"
      :style="styles"
    />
  </div>
</template>

<script>
import { ScreenshotCache } from '@/utils/cache'

export default {
  name: 'DeviceScreenShot',
  props: {
    device: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      asking: false,
      styles: null
    }
  },
  created () {
    ScreenshotCache.watch(this.device, this.onScreenshotUpdate, 10000)
  },
  activated () {
    ScreenshotCache.watch(this.device, this.onScreenshotUpdate, 10000)
  },
  beforeDestroy () {
    ScreenshotCache.unwatch(this.device.id)
  },
  methods: {
    onScreenshotUpdate ({ waiting, base64 }) {
      this.asking = waiting
      this.styles = !waiting && base64 ? { backgroundImage: `url("${base64}")` } : null
    },
    invoke () {
      ScreenshotCache.screenshot(this.device.id)
    }
  }
}
</script>

<style lang="scss" scoped>
.o-icon {
  background-image: url("~@/assets/icon_screenshot.png");

  &.o-device-grid-item__icon {
    background-image: url("~@/assets/icon_image.png");
  }
}
</style>
