<template>
  <v-dialog
    v-if="url"
    v-model="dialog"
    max-width="600px"
    scrollable>
    <template #activator="{ on }">
      <v-img
        :width="width"
        :max-width="maxWidth"
        :height="height"
        :src="url"
        :alt="url"
        :contain="contain"
        :class="{ 'cs-pointer': preview }"
        class="bg-transparent"
        aspect-ratio="1"
        v-on="preview ? on : $listeners"
        @error="getFallback()">
        <template #placeholder>
          <v-row
            class="fill-height ma-0"
            align="center"
            justify="center">
            <v-progress-circular
              color="primary"
              size="14"
              width="1"
              indeterminate />
          </v-row>
        </template>
      </v-img>
    </template>
    <v-card>
      <v-card-title>
        <v-spacer />
        <v-btn
          color="#A9A9A9"
          x-small
          icon
          @click="setDialog(false)">
          <v-icon small>
            mdi-close
          </v-icon>
        </v-btn>
      </v-card-title>
      <v-card-text class="text-center">
        <img
          :src="previewUrl"
          :alt="previewUrl"
          @error="getFallbackPreview()" />
      </v-card-text>
    </v-card>
  </v-dialog>
</template>

<script>
import imgEmpty from '../../assets/imgs/thumb-placeholder.png'

export default {
  props: {
    src: {
      type: String,
      default: ''
    },
    preview: {
      type: String,
      default: ''
    },
    maxWidth: {
      type: [String, Number],
      default: undefined
    },
    width: {
      type: [String, Number],
      default: '100'
    },
    height: {
      type: [String, Number],
      default: '100'
    },
    contain: Boolean
  },
  data () {
    return {
      dialog: false,
      url: null,
      previewUrl: null
    }
  },
  watch: {
    src: {
      immediate: true,
      handler (newValue) {
        this.url = newValue || imgEmpty
      }
    },
    preview: {
      immediate: true,
      handler (newValue) {
        this.previewUrl = newValue || imgEmpty
      }
    }
  },
  methods: {
    setDialog (dialog = false) {
      this.dialog = dialog
    },
    getFallback () {
      this.url = imgEmpty
    },
    getFallbackPreview () {
      this.previewUrl = imgEmpty
    }
  }
}
</script>
