<template>
  <div class="svga-player" v-on="$listeners">
    <canvas :class="className"></canvas>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';
import { Lock, Random, isCorrespondingPlatform } from '../utils';
import SvgaPlayer from './SvgaPlayer';

export default Vue.extend({
  props: {
    src: {
      type: String,
      required: true,
    },
    options: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      player: null,
      className: 'canvas',
      lock: new Lock(),
    };
  },
  methods: {
    async init(src: string) {
      this.className = `canvas-${Random.getRandomLowercaseString(7)}`;
      await this.$nextTick();
      const {
        cacheSvga = !isCorrespondingPlatform('IOS'),
        cacheTiemout = 5000,
        cacheFrames = false,
        intersectionObserverRender = false,
        ...options
      } = this.options;
      const svgaOptions = {
        src,
        element: '.' + this.className,
        cacheSvga: cacheSvga,
        cacheTiemout,
        cacheFrames,
        intersectionObserverRender,
        ...options,
        listener: (type: string) => {
          this.$emit(type);
        },
      };

      // @ts-ignore
      this.player = new SvgaPlayer(svgaOptions);
    },
    start() {
      if (this.player) {
        // @ts-ignore
        this.player.start();
      }
    },
    pause() {
      if (this.player) {
        // @ts-ignore
        this.player.pause();
      }
    },

    resume() {
      if (this.player) {
        // @ts-ignore
        this.player.resume();
      }
    },

    stop() {
      if (this.player) {
        // @ts-ignore
        this.player.stop();
      }
    },

    clear() {
      if (this.player) {
        // @ts-ignore
        this.player.clear();
      }
    },
  },
  async created() {
    try {
      const src = this.src;
      await this.lock.lock();
      await this.init(src);
    } finally {
      this.lock.unlock();
    }
  },
  async beforeDestroy() {
    try {
      await this.lock.lock();
      if (this.player) {
        (this.player as SvgaPlayer).destroy();
      }
    } finally {
      this.lock.unlock();
    }
  },
});
</script>
