import cPickle
import re
import os
import time

import lasso

from quixote import get_publisher, get_request

from hosts import Host

def get_abs_path(s):
    if not s:
        return s
    if s[0] == '/':
        return s
    return os.path.join(get_publisher().app_dir, s)

def get_root_url():
    req = get_request()
    return '%s://%s%s' % (req.get_scheme(), req.get_server(), req.environ['SCRIPT_NAME'])

def get_proxied_site_path():
    host = Host.get_host_from_url()
    if host is None:
        return None
    return host.site_dir

def get_proxied_site_domain():
    return get_request().get_server().split(':')[0]

def get_proxied_site_name():
    nb_subdirs = get_request().environ['SCRIPT_NAME'].count('/')
    return get_request().get_path().split('/')[nb_subdirs + 2]

def get_lasso_server(protocol = 'liberty'):
    host = Host.get_host_from_url()
    if host is None:
        return None
    proxied_site_path = get_proxied_site_path()
    if protocol == 'liberty':
        server = lasso.Server(
            os.path.join(proxied_site_path, 'metadata.xml'),
            os.path.join(proxied_site_path, 'private_key.pem'),
            None, None)
#     elif protocol == 'saml2' and cfg['sp'].has_key('saml2_metadata'):
#         server = lasso.Server(
#             os.path.join(proxied_site_path, 'metadata.xml'),
#             os.path.join(proxied_site_path, 'private_key.pem'),
#             None, None)
    else:
        raise 'XXX: unknown protocol'

    reload_cfg()    
    idps_dir = get_abs_path('idp')
    if cfg.has_key('idp'):
        idp_dir = os.path.join(idps_dir, cfg['idp'])
        public_key_path = os.path.join(idp_dir, 'public_key.pem')
        if not os.path.isfile(public_key_path):
            public_key_path = None
        ca_cert_chain = os.path.join(idp_dir, 'ca_cert_chain.pem')
        if not os.path.isfile(ca_cert_chain):
            ca_cert_chain = None
        try:
            server.addProvider(
                    lasso.PROVIDER_ROLE_IDP,
                    os.path.join(idp_dir, 'metadata.xml'),
                    public_key_path,
                    ca_cert_chain)
        except lasso.Error, error:
            if error[0] == -203: # protocol mismatch
                return None
            if error[0] == -202: # failed to add new provider
                return None
            raise

    return server

def get_provider_label(provider):
    if not provider:
        return None
    if not hasattr(provider, str('getOrganization')):
        return provider.providerId

    organization = provider.getOrganization()
    if not organization:
        return provider.providerId

    name = re.findall("<OrganizationDisplayName.*>(.*?)</OrganizationDisplayName>", organization)
    if not name:
        name = re.findall("<OrganizationName.*>(.*?)</OrganizationName>", organization)
        if not name:
            return provider.providerId
    return name[0]


def write_cfg(directory = None):
    s = cPickle.dumps(cfg)
    if directory is None:
        filename = os.path.join(get_publisher().app_dir, 'config.pck')
    else:
        filename = os.path.join(directory, 'config.pck')
    file(filename, 'w').write(s)

def reload_cfg():
    global cfg
    filename = os.path.join(get_publisher().app_dir, 'config.pck')
    try:
        cfg = cPickle.load(file(filename))
        cfg['debug'] = {}
        cfg['debug']['logger'] = True
    except:
        cfg = {}

def date_format():
    lang = cfg.get('language', {}).get('language', None)
    format_string = '%Y-%m-%d'
    return format_string
