import { Browser, OS } from 'mweb/common/reducers/device';

interface UserAgentInfo {
  os: OS;
  browser: Browser;
}

export function convertUserAgentToBrowserAndOS(
  userAgent: string,
): UserAgentInfo {
  /**
   * These are purposefully ordered because Windows Phone "lies" about itself
   * in order to not be treated as desktop IE and includes Android in its UA.
   *
   * Also note that Fire OS does not identify itself as Fire. You have to infer
   * it from the usage of Silk. But, since they have different app stores and
   * our app has different IDs we have to be able to tell them apart.
   *
   * The list is also not exhaustive, making assumptions about os and browser
   * until greater specficity is demanded by app features.
   */

  if (/iPad|iPhone|iPod/.test(userAgent)) {
    if (/CriOS/.test(userAgent)) {
      return {
        os: OS.iOS,
        browser: Browser.Chrome,
      };
    }

    return {
      os: OS.iOS,
      browser: Browser.Safari,
    };
  } else if (/IEMobile|Windows Phone/.test(userAgent)) {
    return {
      os: OS.Microsoft,
      browser: Browser.Edge,
    };
  } else if (/\bSilk\b/.test(userAgent)) {
    return {
      os: OS.Fire,
      browser: Browser.Silk,
    };
  } else if (/Android/.test(userAgent)) {
    return {
      os: OS.Android,
      browser: Browser.Chrome,
    };
  }

  return {
    os: OS.Other,
    browser: Browser.Other,
  };
}
