<template>
  <div class="l-flex--col c-runtime">
    <div class="l-flex__none l-flex--row has-bottom-padding">
      <i class="l-flex__none c-runtime__icon screenshot" />
      <span class="l-flex__fill c-runtime__title 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-invoke u-pointer"
        @click="invoke"
      />
    </div>
    <div
      class="l-flex__fill o-preview"
      :style="styles"
    />
  </div>
</template>

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

export default {
  name: 'DeviceScreenShot',
  props: {
    device: {
      type: Object,
      default: null
    }
  },
  data () {
    return {
      asking: false,
      styles: null
    }
  },
  activated () {
    ScreenshotCache.watch(this.device, this.onScreenshotUpdate, 10000)
  },
  created () {
    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-invoke {
  display: inline-block;
  width: 24px;
  height: 24px;
  background: url("~@/assets/icon_screenshot.png") 0 0 / 100% 100% no-repeat;
}

.o-preview {
  background-position: center center;
  background-size: contain;
  background-repeat: no-repeat;
}
</style>
