import { defineComponent } from '@vue/composition-api';
import { bridgeVideoBlobGet } from '@/bridge/options/background';
import { loggerShopee } from '@/plugins/logger';

export default defineComponent({
  data() {
    return {
      source: 'tiktok',
      videoUrl: '',
      sourceUrl: '',
      videoBlob: null,
      loadError: false,
    };
  },
  computed: {
    sourceLabel() {
      if (this.source === 'shopee') {
        return 'Shopee';
      }

      return 'TikTok';
    },
  },
  beforeDestroy() {
    if (this.videoUrl && this.videoUrl.indexOf('blob:') === 0) {
      URL.revokeObjectURL(this.videoUrl);
    }
  },
  methods: {
    async loadVideoFromBlob(blobId) {
      try {
        const entry = await bridgeVideoBlobGet(blobId);

        if (!(entry && entry.base64)) {
          return;
        }

        const blob = this.base64ToBlob(entry.base64, entry.contentType || 'video/mp4');

        this.videoBlob = blob;
        this.videoUrl = URL.createObjectURL(blob);
      } catch (error) {
        loggerShopee.error({
          msg: 'SHOPEE_VIDEO_LOAD_BLOB_ERROR',
          error,
        });
      }
    },
    /**
     *
     * @param {string} base64
     * @param {string} contentType
     * @returns {Blob}
     */
    base64ToBlob(base64, contentType) {
      const byteChars = atob(base64);
      const length = byteChars.length;
      const bytes = new Uint8Array(length);

      for (let i = 0; i < length; i += 1) {
        bytes[i] = byteChars.charCodeAt(i);
      }

      return new Blob([bytes], { type: contentType });
    },
  },
});
