import cStringIO
import cPickle
import re
import os
import lasso
import glob
import zipfile

from quixote import get_publisher, get_request, get_response, redirect
from quixote.directory import Directory, AccessControlled

from qommon.form import *
from qommon.misc import get_abs_path
from qommon.admin.cfg import cfg_submit
from qommon.admin.menu import html_top, error_page
from qommon.admin.emails import EmailsDirectory as QommonEmailsDirectory
from qommon.admin.settings import SettingsDirectory as QommonSettingsDirectory

from larpe import misc
from larpe.hosts import Host
from larpe.admin.liberty_utils import *

class LibertyIDPDir(Directory):
    _q_exports = ['', ('metadata.xml', 'metadata')]

    def _q_index [html] (self):
        form = Form(enctype="multipart/form-data")
        form.add(FileWidget, "metadata", title = _("Metadata"), required=True)
        form.add(FileWidget, "publickey", title = _("Public Key"), required=False)
        form.add(FileWidget, "cacertchain", title = _("CA Certificate Chain"), required=False)
        form.add_submit("submit", _("Submit"))

        if not form.is_submitted() or form.has_errors():
            html_top('settings', title = _('New Identity Provider'))
            "<h2>%s</h2>" % _('New Identity Provider')
            form.render()
        else:
            self.submit_new(form)

    def submit_new(self, form, key_provider_id = None):
        metadata, publickey, cacertchain = None, None, None
        if form.get_widget('metadata').parse():
            metadata = form.get_widget('metadata').parse().fp.read()
        if form.get_widget('publickey').parse():
            publickey = form.get_widget('publickey').parse().fp.read()
        if form.get_widget('cacertchain').parse():
            cacertchain = form.get_widget('cacertchain').parse().fp.read()

        if not key_provider_id:
            try:
                provider_id = re.findall(r'(provider|entity)ID="(.*?)"', metadata)[0][1]
            except IndexError:
                return error_page('settings', _('Bad metadata'))
            key_provider_id = provider_id.replace(str('://'), str('-')).replace(str('/'), str('-'))

        dir = get_abs_path(os.path.join('idp', key_provider_id))
        if not os.path.isdir(dir):
            os.makedirs(dir)

        if metadata:
            metadata_fn = os.path.join(dir, 'metadata.xml')
            open(metadata_fn, 'w').write(metadata)
        if publickey:
            publickey_fn = os.path.join(dir, 'public_key')
            open(publickey_fn, 'w').write(publickey)
        else:
            publickey_fn = None
        if cacertchain:
            cacertchain_fn = os.path.join(dir, 'ca_cert_chain.pem')
            open(cacertchain_fn, 'w').write(cacertchain)
        else:
            cacertchain_fn = None

        p = lasso.Provider(lasso.PROVIDER_ROLE_IDP, metadata_fn, publickey_fn, None)

        try:
            misc.get_provider_label(p)
            get_publisher().cfg['idp'] = key_provider_id
            get_publisher().write_cfg()
        except TypeError:
            if metadata:
                os.unlink(metadata_fn)
            if publickey:
                os.unlink(publickey_fn)
            if cacertchain:
                os.unlink(cacertchain_fn)
            return error_page('settings', _('Bad metadata'))

        redirect('..')

    def metadata(self):
        response = get_response()
        response.set_content_type('text/xml', 'utf-8')
        get_publisher().reload_cfg()
        if get_publisher().cfg['idp']:
            idp_metadata = os.path.join(get_abs_path('idp'), get_publisher().cfg['idp'], 'metadata.xml')
            return unicode(open(idp_metadata).read(), 'utf-8')
        return 'No IDP is configured'


class EmailsDirectory(QommonEmailsDirectory):
    def _q_index [html] (self):
        # Don't use custom emails
        html_top('settings', title = _('Emails'))
        '<h2>%s</h2>' % _('Emails')

        '<ul>'
        '<li><a href="options">%s</a></li>' % _('General Options')
        '</ul>'

        '<p>'
        '<a href="..">%s</a>' % _('Back')
        '</p>'


class SettingsDirectory(QommonSettingsDirectory):
    _q_exports = ['', 'liberty_sp', 'liberty_idp', 'domain_names', 'apache2_configuration_generation',
                  'proxy', 'language', 'emails', 'debug_options' ]

    liberty_idp = LibertyIDPDir()
    emails = EmailsDirectory()

    def _q_index [html] (self):
        get_publisher().reload_cfg()
        html_top('settings', title = _('Settings'))

        if lasso.SAML2_SUPPORT:
            '<h2>%s</h2>' % _('Liberty Alliance & SAML 2.0 Service Provider')
        else:
            '<h2>%s</h2>' % _('Liberty Alliance Service Provider')
        '<dl> <dt><a href="liberty_sp">%s</a></dt> <dd>%s</dd>' % (
                _('Service Provider'), _('Configure Larpe as a Service Provider'))

        hosts = Host.select(lambda x: x.name == 'larpe')
        if hosts:
            self.host = hosts[0]

            if lasso.SAML2_SUPPORT and self.host.saml2_metadata is not None:
                metadata_url = '%s/metadata.xml' % self.host.saml2_base_url
                '<dt><a href="%s">%s</a></dt> <dd>%s</dd>' % (
                        metadata_url,
                        _('SAML 2.0 Metadata'),
                        _('Download SAML 2.0 metadata file for Larpe'))

            if self.host.metadata is not None:
                metadata_url = '%s/metadata.xml' % self.host.base_url
                '<dt><a href="%s">%s</a></dt> <dd>%s</dd>' % (
                        metadata_url,
                        _('ID-FF 1.2 Metadata'),
                        _('Download ID-FF 1.2 metadata file for Larpe'))

            if self.host.public_key is not None:
                public_key_url = '%s/public_key' % self.host.base_url
                '<dt><a href="%s">%s</a></dt> <dd>%s</dd>' % (
                        public_key_url,
                        _('Public key'),
                        _('Download SSL Public Key file'))

        if lasso.SAML2_SUPPORT:
            '<h2>%s</h2>' % _('Liberty Alliance & SAML 2.0 Identity Provider')
        else:
            '<h2>%s</h2>' % _('Liberty Alliance Identity Provider')

        '<dl>'

        '<dt><a href="liberty_idp/">%s</a></dt> <dd>%s</dd>' % (
               _('Identity Provider'), _('Configure an identity provider'))

        if get_publisher().cfg.has_key('idp'):
            '<dt><a href="liberty_idp/metadata.xml">%s</a></dt> <dd>%s</dd>' % (
                    _('Identity Provider metadatas'), _('See current identity provider metadatas'))

        '</dl>'

        '<h2>%s</h2>' % _('Global parameters for the sites')

        '<dl>'
        '<dt><a href="domain_names">%s</a></dt> <dd>%s</dd>' % (
                _('Domain name'), _('Configure the base domain name for the sites'))
        '<dt><a href="apache2_configuration_generation">%s</a></dt> <dd>%s</dd>' % (
                _('Apache 2 configuration generation'), _('Customise Apache 2 configuration generation'))
        '<dt><a href="proxy">%s</a></dt> <dd>%s</dd>' % (
                _('Proxy'), _('Connect to the sites through a web proxy'))
        '</dl>'

        '<h2>%s</h2>' % _('Customisation')

        '<dl>'
        '<dt><a href="language">%s</a></dt> <dd>%s</dd>' % (
                _('Language'), _('Configure site language'))
        '<dt><a href="emails/">%s</a></dt> <dd>%s</dd>' % (
                _('Emails'), _('Configure email settings'))
        '</dl>'

        '<h2>%s</h2>' % _('Misc')

        '<dl>'
        '<dt><a href="debug_options">%s</a></dt> <dd>%s</dd>' % (
                _('Debug Options'), _('Configure options useful for debugging'))
        '</dl>'


    def liberty_sp [html] (self):
        get_publisher().reload_cfg()

        # Get the host object for the reverse proxy
        hosts = Host.select(lambda x: x.name == 'larpe')
        if hosts:
            self.host = hosts[0]
        else:
            self.host = Host()
            self.host.reversed_hostname = get_publisher().cfg[str('proxy_hostname')]

        form = Form(enctype='multipart/form-data')
        form.add(StringWidget, 'organization_name', title=_('Organisation Name'), size=50,
                required = True, value = self.host.organization_name)
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))
        if form.get_widget('cancel').parse():
            return redirect('.')
        if not form.is_submitted() or form.has_errors():
            html_top('settings', title = _('Service Provider Configuration'))
            '<h2>%s</h2>' % _('Service Provider Configuration')
            form.render()
        else:
            self.liberty_sp_submit(form)
            redirect('.')

    def liberty_sp_submit(self, form):
        get_publisher().reload_cfg()
        metadata_cfg = {}

        f = 'organization_name'
        if form.get_widget(f):
            setattr(self.host, f, form.get_widget(f).parse())

        metadata_cfg['organization_name'] = self.host.organization_name

        self.host.name = 'larpe'

        # Liberty Alliance / SAML parameters
        base_url = '%s/liberty/%s/liberty' % (misc.get_root_url(), self.host.name)
        metadata_cfg['base_url'] = base_url
        self.host.base_url = base_url

        if lasso.SAML2_SUPPORT:
            saml2_base_url = '%s/liberty/%s/saml' % (misc.get_root_url(), self.host.name)
            metadata_cfg['saml2_base_url'] = saml2_base_url
            self.host.saml2_base_url = saml2_base_url

        provider_id = '%s/metadata' % base_url
        metadata_cfg['provider_id'] = provider_id
        self.host.provider_id = provider_id

        if lasso.SAML2_SUPPORT:
            saml2_provider_id = '%s/metadata' % saml2_base_url
            metadata_cfg['saml2_provider_id'] = saml2_provider_id
            self.host.saml2_provider_id = saml2_provider_id

        # Storage directories
        site_dir = os.path.join(get_publisher().app_dir, 'sp',
                    self.host.reversed_hostname, self.host.name)
        user_dir = os.path.join(site_dir, 'users')
        token_dir = os.path.join(site_dir, 'tokens')
        for dir in (site_dir, user_dir, token_dir):
            if not os.path.isdir(dir):
                os.makedirs(dir)
        metadata_cfg['site_dir'] = site_dir
        self.host.site_dir = site_dir

        # Generate SSL keys
        private_key_path = os.path.join(site_dir, 'private_key.pem')
        public_key_path = os.path.join(site_dir, 'public_key')
        if not os.path.isfile(private_key_path) or not os.path.isfile(public_key_path):
            set_provider_keys(private_key_path, public_key_path)
        self.host.private_key = private_key_path
        metadata_cfg['signing_public_key'] = open(public_key_path).read()
        self.host.public_key = public_key_path

        # Write metadatas
        metadata_path = os.path.join(site_dir, 'metadata.xml')
        open(metadata_path, 'w').write(get_metadata(metadata_cfg))
        self.host.metadata = metadata_path

        if hasattr(self.host, 'saml2_provider_id'):
            saml2_metadata_path = os.path.join(site_dir, 'saml2_metadata.xml')
            open(saml2_metadata_path, 'w').write(get_saml2_metadata(metadata_cfg))
            self.host.saml2_metadata = saml2_metadata_path

        self.host.root_url = '%s/' % misc.get_root_url()
        self.host.return_url = '%s/admin/' % misc.get_root_url()

        self.host.store()

    def domain_names [html] (self):
        form = self.form_domain_name()

        if form.get_widget('cancel').parse():
            return redirect('.')

        if not form.is_submitted() or form.has_errors():
            html_top('settings', title = _('Domain name'))
            '<h2>%s</h2>' % _('Domain name')
            form.render()
        else:
            self.submit_domain_name(form)
            redirect('.')

    def form_domain_name(self):
        get_publisher().reload_cfg()
        if get_cfg('domain_names'):
            domain_name = get_cfg('domain_names')[0]
        else:
            domain_name = None

        form = Form(enctype='multipart/form-data')
        form.add(StringWidget, 'domain_name',
            title=_('Domain name for the sites'),
            value = domain_name)
        # TODO: Add the option "Both" and handle it in hosts configuration
        form.add(SingleSelectWidget, 'sites_url_scheme', title = _('Use HTTP or HTTPS'),
                value = get_cfg('sites_url_scheme'),
                options = [ (None, _('Same as the site')),
                            ('http', 'HTTP'),
                            ('https', 'HTTPS') ] )
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))
        return form

    def submit_domain_name(self, form):
        get_publisher().reload_cfg()
        get_publisher().cfg['domain_names'] = [ form.get_widget('domain_name').parse() ]
        get_publisher().cfg['sites_url_scheme'] = form.get_widget('sites_url_scheme').parse()
        get_publisher().write_cfg()

    def apache2_configuration_generation [html] (self):
        get_publisher().reload_cfg()

        form = Form(enctype='multipart/form-data')
        form.add(CheckboxWidget, 'allow_config_generation',
                title=_('Automatically generate Apache 2 configuration for new hosts and reload Apache 2 after changes'),
                value = get_publisher().cfg.get(str('allow_config_generation'), True))
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))
        if form.get_widget('cancel').parse():
            return redirect('.')
        if not form.is_submitted() or form.has_errors():
            html_top('settings', title = _('Apache 2 configuration generation'))
            '<h2>%s</h2>' % _('Apache 2 configuration generation')
            form.render()
        else:
            self.apache2_configuration_generation_submit(form)
            redirect('.')

    def apache2_configuration_generation_submit(self, form):
        get_publisher().reload_cfg()

        f = 'allow_config_generation'
        get_publisher().cfg[f] = form.get_widget(f).parse()

        get_publisher().write_cfg()
