import { defineComponent } from '@vue/composition-api';
import { getShopeeSellerInfo } from '@/api/shopee/seller/get';
import {
  apiShopeeVideoCampaignList,
  apiShopeeVideoCampaignCreate,
} from '@/api/autoshopee/shopee/shopeeVideo';

export default defineComponent({
  data() {
    return {
      shopId: '',
      shopName: '',
      campaigns: [],
      campaignName: '',
    };
  },
  computed: {
    hasCampaign() {
      return !!this.campaignName.trim();
    },
    campaignSuggestions() {
      const keyword = this.campaignName.trim().toLowerCase();

      if (!keyword) {
        return this.campaigns;
      }

      return this.campaigns.filter((campaign) => {
        return `${campaign.name}`.toLowerCase().indexOf(keyword) >= 0;
      });
    },
  },
  methods: {
    async loadShopAndCampaigns() {
      const sellerInfo = await getShopeeSellerInfo();

      if (sellerInfo && sellerInfo.shop_id) {
        this.shopId = `${sellerInfo.shop_id}`;
        this.shopName = sellerInfo.name || '';
      }

      if (!this.shopId) {
        return;
      }

      const fresh = await apiShopeeVideoCampaignList(this.shopId);

      this.campaigns = Array.isArray(fresh) ? fresh : [];

      if (!this.campaignName) {
        const last = this.readLastCampaign();

        if (last) {
          this.campaignName = last;
        }
      }
    },
    lastCampaignKey() {
      return `sv-video-last-campaign-${this.shopId}`;
    },
    readLastCampaign() {
      try {
        return window.sessionStorage.getItem(this.lastCampaignKey()) || '';
      } catch (error) {
        return '';
      }
    },
    writeLastCampaign(name) {
      try {
        window.sessionStorage.setItem(this.lastCampaignKey(), name);
      } catch (error) {
        // ignore storage errors
      }
    },
    /**
     *
     * @returns {Promise<string>}
     */
    async resolveCampaignId() {
      const name = this.campaignName.trim();

      if (!name) {
        return '';
      }

      const existing = this.campaigns.find((campaign) => {
        return `${campaign.name}`.trim().toLowerCase() === name.toLowerCase();
      });

      if (existing && existing._id) {
        this.writeLastCampaign(name);
        return existing._id;
      }

      const created = await apiShopeeVideoCampaignCreate({
        name,
        shopId: this.shopId,
        shopName: this.shopName,
      });

      if (created && created._id) {
        this.campaigns = [created].concat(this.campaigns);
        this.writeLastCampaign(name);
        return created._id;
      }

      return '';
    },
  },
});
