import { OS } from 'mweb/common/reducers/device';
import { Location } from 'mweb/common/reducers/app';

export const IOS_INTERSTITIAL_BASE_URL = `https://u.m.twitch.tv`;
const PLAY_STORE_APP_ID = 'tv.twitch.android.app';
const AMAZON_APP_STORE_APP_ID = 'tv.twitch.android.viewer';

type Campaign = Location;

interface AppStoreOpts {
  os: OS;
  campaign: Campaign;
  callToActionIdentifier: string;
}

interface DeepLinkOpts {
  path: string;
  referrer: string;
  appStoreOpts?: AppStoreOpts;
}

export function buildDeepLinkURL(opts: DeepLinkOpts): string {
  if (!opts.appStoreOpts) {
    return `twitch://m.twitch.tv${opts.path}?referrer=${encodeURIComponent(
      opts.referrer,
    )}`;
  }
  switch (opts.appStoreOpts.os) {
    case OS.iOS:
      return buildiOSDeepLinkURL(
        opts.path,
        opts.appStoreOpts.campaign,
        opts.appStoreOpts.callToActionIdentifier,
      );
    case OS.Android:
      return buildAndroidDeepLinkURL(
        opts.referrer,
        opts.path,
        opts.appStoreOpts.campaign,
        PLAY_STORE_APP_ID,
      );
    case OS.Fire:
      return buildAndroidDeepLinkURL(
        opts.referrer,
        opts.path,
        opts.appStoreOpts.campaign,
        AMAZON_APP_STORE_APP_ID,
        false,
      );
    default:
      return '';
  }
}

function buildiOSDeepLinkURL(
  path: string,
  campaign: Campaign,
  callToActionIdentifier: string,
): string {
  return `${IOS_INTERSTITIAL_BASE_URL}${path}?c=${campaign}-${callToActionIdentifier}`;
}

function buildAndroidDeepLinkURL(
  referrer: string,
  path: string,
  campaign: Campaign,
  appID: string,
  haveFallback: boolean = true,
): string {
  // doubly encode the referrer to avoid break on & in urls params, etc
  const encodedMarketURL = encodeURIComponent(`market://details?id=${appID}`);
  // There seems to be a weird Chrome bug where if it goes source then medium then the params
  // passed to the play store cause it to not load the Twitch app up in the store if the app
  // was previously running. However, putting them in this order makes it work fine.
  const encodedMarketReferrer = encodeURIComponent(
    `utm_campaign=${encodeURIComponent(campaign)}&utm_source=mwc`,
  );
  return (
    `intent://m.twitch.tv${path}?referrer=${encodeURIComponent(referrer)}` +
    `#Intent;package=${appID};scheme=twitch;` +
    `S.market_referrer=${encodedMarketReferrer};` +
    (haveFallback ? `S.browser_fallback_url=${encodedMarketURL};` : '') +
    `end;`
  );
}
