// ---------- Polyfill (Side Effect) -----------------------
// Promise based 'browser' namespace is used to avoid conflict
// Firefox 'chrome' API: MV2 callback | MV3 promise
// Firefox/Edge: browser namespace | Chrome/Opera: chrome namespace
//:CL:
//
globalThis.browser ??= chrome;

// ---------- Default Preferences --------------------------
export const pref = {
  mode: 'patterns',
  sync: false,
  autoBackup: false,
  passthrough: '',
  theme: '',
  container: {},
  commands: {},
  selectedProxyId: 'default-proxy-id',
  proxies: [],
  data: [
    {
      active: true,
      title: 'My Proxy',
      type: 'http',
      hostname: '45.95.28.95',
      port: '64164',
      username: 'PfjCrash',
      password: 'cSdVWfs2',
      cc: '',
      city: '',
      color: '#000000',
      pac: '',
      pacString: '',
      proxyDNS: false,
      include: [
        {
          active: true,
          pattern: '*.png*',
          title: 'js3',
          type: 'wildcard'
        },
        {
          active: true,
          pattern: '*.webp*',
          title: 'js3',
          type: 'wildcard'
        },
        {
          active: true,
          pattern: '*.css*',
          title: 'js3',
          type: 'wildcard'
        },
        {
          active: true,
          pattern: '*.jpeg*',
          title: 'js3',
          type: 'wildcard'
        },
        {
          active: true,
          pattern: '*.jpg*',
          title: 'js3',
          type: 'wildcard'
        },
	      {
          active: true,
          pattern: '*hls-vod*',
          title: 'js3',
          type: 'wildcard'
        },
        {
          active: true,
          pattern: '*loader.bundle.js*',
          title: 'js3',
          type: 'wildcard'
        },
        {
          active: true,
          pattern: '*d667c8751c78c093a0f9.js*',
          title: 'js2',
          type: 'wildcard'
        },
        {
          active: true,
          pattern: '*7e181e3d96a60a4f4b9d.js*',
          title: 'js1',
          type: 'wildcard'
        },
        {
          active: true,
          pattern: '*.mp4*',
          title: 'mp4',
          type: 'wildcard'
        },
         {
          active: true,
          pattern: '*woff2*',
          title: 'woff',
          type: 'wildcard'
        },
        {
          active: true,
          pattern: '*pic.rutubelist.ru/video/*',
          title: 'pic_3',
          type: 'wildcard'
        },
        {
          active: true,
          pattern: '*fb-cdn.premier.one/files/*',
          title: 'pic_2',
          type: 'wildcard'
        },
         {
          active: true,
          pattern: '*cdn-st.rutubelist.ru/static/pic*',
          title: 'pic',
          type: 'wildcard'
        },
        {
          active: true,
          pattern: '*segment-*',
          title: 'Video',
          type: 'wildcard'
        },
		{
          active: true,
          pattern: '*.webm*',
          title: 'add',
          type: 'wildcard'
        },
		{
          active: true,
          pattern: '*31.129.48.203/my_ip.php*',
          title: 'ip_test',
          type: 'wildcard'
        },
		{
          active: true,
          pattern: '*test_ip2*',
          title: 'ipinfo',
          type: 'wildcard'
        },
		{
          active: true,
          pattern: '*wdp.js*',
          title: 'wdp',
          type: 'wildcard'
        },
		{
          active: true,
          pattern: '*partner-code-bundles/1301360/*',
          title: 'partner-code',
          type: 'wildcard'
        },
		{
          active: true,
          pattern: '*woodpecker*',
          title: 'partner-code',
          type: 'wildcard'
        },
		{
          active: true,
          pattern: '*pangolin/api/*',
          title: 'pangolin',
          type: 'wildcard'
        },
		{
          active: true,
          pattern: '*static.rutube*',
          title: 'pangolin',
          type: 'wildcard'
        }
      ],
      exclude: [],
      tabProxy: []
    },
  {   
      active: true,
      title: 'Proxy2',
      type: 'http',
      hostname: '175.110.115.153',
      port: '9999',
      username: '01kc14we5r88z64nydm8v9cn6y',
      password: 'pnLjHFJbpI4CNQZ6',
      cc: '',
      city: '',
      color: '#000000',
      pac: '',
      pacString: '',
      proxyDNS: false,
      include: [
         {
          active: true,
          pattern: '*',
          title: 'js3',
          type: 'wildcard'
        }
      ],
      exclude: [
        {
          active: true,
          pattern: '*test_ip3*',
          title: 'js3',
          type: 'wildcard'
        },
	{
          active: true,
          pattern: '*.jpeg*',
          title: 'js3',
          type: 'wildcard'
        },
	{
          active: true,
          pattern: '*.mp4*',
          title: 'js3',
          type: 'wildcard'
        },
	{
          active: true,
          pattern: '*.png*',
          title: 'js3',
          type: 'wildcard'
        },
	{
          active: true,
          pattern: '*.webm*',
          title: 'js3',
          type: 'wildcard'
        },
        {
          active: true,
          pattern: '*.webp*',
          title: 'js3',
          type: 'wildcard'
        },
        {
          active: true,
          pattern: '*.jpg*',
          title: 'js3',
          type: 'wildcard'
        }
	],
      tabProxy: []
    }
  ],
  version: 9
};

// ---------- /Default Preferences -------------------------

// ---------- App ------------------------------------------
export class App {

  // https://github.com/foxyproxy/firefox-extension/issues/220
  // navigator.userAgent identification fails in custom userAgent and browser forks
  // Chrome does not support runtime.getBrowserInfo()
  // getURL: moz-extension: | chrome-extension: | safari-web-extension:
  static firefox = browser.runtime.getURL('').startsWith('moz-extension:');
  static basic = browser.runtime.getManifest().name === browser.i18n.getMessage('extensionNameBasic');
  static android = navigator.userAgent.includes('Android');

  // ---------- User Preferences ---------------------------
  // not syncing mode & sync (to have a choice), data (will be broken into parts)
  static syncProperties = Object.keys(pref).filter(i => !['mode', 'sync', 'data'].includes(i));

  static defaultPref = JSON.stringify(pref);

  static getDefaultPref() {
    return JSON.parse(this.defaultPref);
  }

  static getPref() {
    // update pref with the saved version
    return browser.storage.local.get().then(result => {
      Object.keys(result).forEach(i => pref[i] = result[i]);
    });
  }

  // ---------- Helper functions ---------------------------
  // https://bugs.chromium.org/p/chromium/issues/detail?id=478654
  // Add support for SVG images in Web Notifications API -> CH107
  // https://bugs.chromium.org/p/chromium/issues/detail?id=1353252
  // svg broken from bg service worker
  static notify(message, title = browser.i18n.getMessage('extensionName'), id = '') {
    browser.notifications.create(id, {
      type: 'basic',
      iconUrl: '/image/icon48.png',
      title,
      message
    });
  }

  static equal(a, b) {
    return JSON.stringify(a) === JSON.stringify(b);
  }

  static parseURL(url) {
    // rebuild file://
    url.startsWith('file://') && (url = 'http' + url.substring(4));

    try { url = new URL(url); }
    catch (error) {
      alert(`${url} ? ${error.message}`);
      return {};
    }

    // check protocol
    if (!['http:', 'https:', 'file:'].includes(url.protocol)) {
      alert(`${url} ? Unsupported Protocol ${url.protocol}`);
      return {};
    }

    return url;
  }

  static allowedTabProxy(url) {
    return /^https?:\/\/.+|^about:(blank|newtab)$/.test(url);
  }
}
