import re
import fnmatch
import urllib2
from kodipopcorntime import plugin
from kodipopcorntime.caching import shelf


PAC_URL = "http://clientconfig.immunicity.org/pacs/all.pac"
CACHE = 1 * 3600 # 1 hour caching


_config = {}
def config():
    global _config
    if not _config:
        with shelf("kodipopcorntime.immunicity.pac_config", ttl=CACHE) as pac_config:
            plugin.log.info("Fetching Immunicity PAC file")
            pac_data = urllib2.urlopen(PAC_URL).read()
            pac_config["server"] = re.search(r"var proxyserver = '(.*)'", pac_data).group(1)
            pac_config["domains"] = map(lambda x: x.replace(r"\Z(?ms)", ""), map(fnmatch.translate, re.findall(r"\"(.*?)\",", pac_data)))
            _config = pac_config
    return _config


def get_proxy_for(url):
    conf = config()
    for domain in conf["domains"]:
        if re.search(domain, url):
            return conf["server"]
