var get = chrome.i18n.getMessage;

export var ProxyManager = {
  toolbarButton: null,
  currentProxy: null,
  userAgent: null,
  proxyAuth: null,
  debugMode: false,

  Callback: function(fn, ctx) {
    return function() {
      fn.apply(ctx, arguments);
    }
  },

  SetIcon: function(mode, name, badge) {
    chrome.action.setIcon({
       path: {
         19: './data/img/19/'+mode+'/'+name+'.png',
         38: './data/img/38/'+mode+'/'+name+'.png'
       }
    });
    chrome.action.setBadgeText({text: badge});
  },

  SetupProxy: function(host, port, code, name, user, password, userAgent, siteExpludeList, success) {
    if (this.currentProxy != host) {
      this.currentProxy = host;
      this.userAgent = userAgent;
      this.proxyAuth = (user === null || password === null) ? null : {user: user, password: password};
      port = port.match(/\d+/)[0];
      host = host.match(/[\.\d\w-]+/)[0];

      var siteList = new Array('*proxylistpro.*', '*paypal.*', '*webmoney.*', '*perfectmoney.*');
      for (i in siteExpludeList)
        if (siteExpludeList[i].length > 0)
          siteList.push('*'+siteExpludeList[i]+'*');

      chrome.proxy.settings.set({
         value: {
           mode: 'pac_script',
           pacScript: {
             data: 'function FindProxyForURL(url, host) {if (shExpMatch(host, "('+siteList.join('|')+')")) return "DIRECT"; return "'+((/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/i).test(host) ? 'PROXY' : 'HTTPS')+' '+host+':'+port+'";}'
           }
         },
         scope: 'regular'
      }, function() {});
      if (this.debugMode) console.log('Setting proxy "' + host + ':' + port + '" (ProxyManager.SetupProxy)');

      chrome.action.setTitle({title: name});
    }
    if (success && typeof success === 'function')
      success();
  },

  RestoreProxy: function(success) {
    chrome.proxy.settings.clear({scope: 'regular'}, function() {
      if (success && typeof success === 'function')
        success();
    });
    this.currentProxy = null;
    this.userAgent = null;
    if (this.debugMode) console.log('Restoring proxy (ProxyManager.RestoreProxy)');

    chrome.action.setTitle({title: get('app_name')});

    if (success && typeof success === 'function')
      success();
  },

  HardReset: function() {
    if (this.debugMode) console.log('Resetting proxy settings (ProxyManager.HardReset)');
    chrome.proxy.settings.clear({scope: 'regular'});
  }
}