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 menu import *

from larpe.qommon.form import *
from larpe.qommon.admin.emails import EmailsDirectory

from larpe.template import DEFAULT_TEMPLATE_EZT
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(_('Bad metadata'))
            key_provider_id = provider_id.replace(str('://'), str('-')).replace(str('/'), str('-'))

        dir = misc.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')
            file(metadata_fn, 'w').write(metadata)
        if publickey:
            publickey_fn = os.path.join(dir, 'public_key.pem')
            file(publickey_fn, 'w').write(publickey)
        else:
            publickey_fn = None
        if cacertchain:
            cacertchain_fn = os.path.join(dir, 'ca_cert_chain.pem')
            file(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)
            misc.cfg['idp'] = key_provider_id
            misc.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(_('Bad metadata'))

        redirect('..')

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


class EmailsDirectory(Directory):
    emails = []

    def __init__(self):
        self._q_exports = ['', 'options'] + [x[0] for x in self.emails]

    def options [html] (self):
        form = Form(enctype="multipart/form-data")
        emails = misc.cfg.get('emails', {})
        form.add(StringWidget, 'smtp_server', title = _('SMTP Server'),
                required = False, value = emails.get('smtp_server', ''))
        form.add(StringWidget, 'from', title = _('Email Sender'),
                required = True, value = emails.get('from', 'larpe@localhost'))
        form.add(StringWidget, 'reply_to', title = _('Reply-To Address'),
                required = False, value = emails.get('reply_to'))

        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 = _('Emails'))
            "<h2>%s</h2>" % _('General Options')
            form.render()
        else:
            self.options_submit(form)
            redirect('.')

    def options_submit(self, form):
        misc.reload_cfg()
        if not misc.cfg.has_key('emails'):
            misc.cfg['emails'] = {}
        for k in ('smtp_server', 'from', 'reply_to'):
            misc.cfg['emails'][k] = form.get_widget(k).parse()
        misc.write_cfg()

    def _q_index [html] (self):
        html_top('settings', title = _('Emails'))
        '<h2>%s</h2>' % _('Emails')

        '<ul>'
        '<li><a href="options">%s</a></li>' % _('General Options')
        for email_key, email_label in self.emails:
            '<li><a href="%s">%s %s</a></li>' % (email_key,
                    _('Custom Email:'), _(email_label))
        '</ul>'

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


    def email [html] (self, email_key, email_label, hint = None, check_template = None,
                enabled = True):
        emails_cfg = misc.cfg.get('emails', {})
        cfg_key = 'email-%s' % email_key

        form = Form(enctype='multipart/form-data')
        form.add(CheckboxWidget, cfg_key + '_enabled', title = _('Enabled Email'),
                value = emails_cfg.get(cfg_key + '_enabled', True), default = enabled)
        form.add(StringWidget, cfg_key + '_subject', title = _('Subject'),
                value = emails_cfg.get(cfg_key + '_subject', ''))
        form.add(TextWidget, cfg_key, title = email_label, value = emails_cfg.get(cfg_key),
                cols = 80, rows = 10, hint = hint)
        form.add_submit('submit', _('Submit'))
        form.add_submit('restore-default', _('Restore default email'))
        form.add_submit('cancel', _('Cancel'))

        if form.get_submit() == 'cancel':
            return redirect('.')

        if form.get_submit() == 'restore-default':
            self.email_submit(None, cfg_key)
            return redirect('.')

        if form.is_submitted() and not form.has_errors():
            if self.email_submit(form, cfg_key, check_template):
                return redirect('.')
            form.set_error(cfg_key, _('Invalid template'))

        html_top('settings', title = _('Emails'))
        '<h2>%s - %s</h2>' % (_('Email'), email_label)
        form.render()

    def email_submit(self, form, cfg_key, check_template = None):
        misc.reload_cfg()
        if not misc.cfg.has_key('emails'):
            misc.cfg['emails'] = {}
        if form:
            template = form.get_widget(cfg_key).parse()
            if check_template and not check_template(template):
                return False
            misc.cfg['emails'][str(cfg_key)] = template
            misc.cfg['emails'][str(cfg_key + '_enabled')] = form.get_widget(
                    cfg_key + '_enabled').parse()
            misc.cfg['emails'][str(cfg_key + '_subject')] = form.get_widget(
                    cfg_key + '_subject').parse()
        else:
            misc.cfg['emails'][str(cfg_key)] = None
        misc.write_cfg()
        return True


class SettingsDirectory(AccessControlled, Directory):
    _q_exports = ['', 'liberty_sp', 'liberty_idp', 'metadata', ('public_key.pem', 'public_key'),
                  'apache2_configuration_generation', 'language', 'emails' ]

    liberty_idp = LibertyIDPDir()
    emails = EmailsDirectory()

    def _q_access(self):
        get_response().breadcrumb.append( ('settings/', _('Settings')) )

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

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

        '<h2>%s</h2>' % _('Liberty Alliance Service Provider')
        '<dl> <dt><a href="liberty_sp">%s</a></dt> <dd>%s</dd>' % (
                _('Service Provider'), _('Configure Liberty Alliance parameters'))

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

            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,
                        _('Service Provider Metadata'),
                        _('Download Service Provider ID-FF 1.2 Metadata file'))

#            if lasso.SAML2_SUPPORT:
#                metadata_url = '%s/metadata.xml' % self.host.saml2_base_url
#                '<dt><a href="%s">%s</a></dt> <dd>%s</dd>' % (
#                        metadata_url,
#                        _('Service Provider Metadata'),
#                        _('Download Service Provider SAML 2.0 Metadata file'))

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

#        if lasso.SAML2_SUPPORT:
#            '<h2>Liberty Alliance & SAML 2.0 Identity Provider</h2>'
#        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 misc.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>' % _('Customisation')

        '<dl>'
        '<dt><a href="apache2_configuration_generation">%s</a></dt> <dd>%s</dd>' % (
                _('Apache 2 configuration generation'), _('Customise Apache 2 configuration generation'))
        '<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="misc">%s</a></dt> <dd>%s</dd>' % (
#                _('Misc'), _('Configure misc options'))
#        '<dt><a href="debug_options">%s</a></dt> <dd>%s</dd>' % (
#                _('Debug Options'), _('Configure options useful for debugging'))
#        '</dl>'


    def liberty_sp [html] (self):
        misc.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 = misc.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_save(form)
            redirect('.')

    def liberty_sp_save(self, form):
        misc.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/saml/%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.pem')
        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)
#            metadata_cfg['privatekey'] = private_key_path
            self.host.private_key = private_key_path
#            metadata_cfg['publickey'] = public_key_path
            self.host.public_key = public_key_path
        
        # Write metadatas
        metadata_path = os.path.join(site_dir, 'metadata.xml')
        file(metadata_path, 'w').write(get_metadata(metadata_cfg))
#        metadata_cfg['metadata'] = metadata_path
        self.host.metadata = metadata_path

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

        # Use default idps
#         idp_dir = os.path.join(get_publisher().app_dir, 'idp')
#         self.host.idps = os.listdir(idp_dir)

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

        self.host.store()

    def metadata(self):
        hosts = Host.select(lambda x: x.name == 'larpe')
        if hosts:
            host = hosts[0]
        else:
            return redirect('%s/admin/' % misc.get_root_url())
        response = get_response()
        response.set_content_type('text/xml', 'utf-8')
        metadata = unicode(open(host.metadata).read(), 'utf-8')
        return metadata

    def public_key(self):
        hosts = Host.select(lambda x: x.name == 'larpe')
        if hosts:
            host = hosts[0]
        else:
            # FIXME : error page ?
            return redirect('.')
        response = get_response()
        response.set_content_type('text/plain')
        public_key = open(host.public_key).read()
        return public_key

    def apache2_configuration_generation [html] (self):
        misc.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 = misc.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):
        misc.reload_cfg()

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

        misc.write_cfg()

    def language [html] (self):
        form = Form(enctype='multipart/form-data')
        language_cfg = misc.cfg.get('language', {})
        form.add(SingleSelectWidget, 'language', title = _('Language'),
                value = language_cfg.get('language'),
                options = [ (None, _('System Default')),
                            (str('en'), _('English')),
                            (str('fr'), _('French')) ] )
         
        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 = _('Language'))
            '<h2>%s</h2>' % _('Language')
            form.render()
        else:
            self.language_submit(form)
            redirect('.')

    def language_submit(self, form):
        misc.reload_cfg()
        if not misc.cfg.has_key('language'):
            misc.cfg['language'] = {}
        for k in ('language', ):
            misc.cfg['language'][k] = form.get_widget(k).parse()
        misc.write_cfg()

#     def debug_options [html] (self):
#         form = Form(enctype="multipart/form-data")
#         debug_cfg = misc.cfg.get('debug', {})
#         form.add(StringWidget, 'error_email', title = _('Email for Tracebacks'),
#                 value = debug_cfg.get('error_email', ''))
#         form.add(SingleSelectWidget, 'display_exceptions', title = _('Display Exceptions'),
#                 value = debug_cfg.get('display_exceptions', ''),
#                 options = [ (str(''), _('No display')),
#                             (str('text'), _('Display as Text')),
#                             (str('text-in-html'), _('Display as Text in HTML an error page')),
#                             (str('html'), _('Display as HTML')) ])
#         form.add(CheckboxWidget, 'logger', title = _('Logger'),
#                 value = debug_cfg.get('logger', False))
#         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 = _('Debug Options'))
#             '<h2>%s</h2>' % _('Debug Options')
#             form.render()
#         else:
#             self.debug_options_submit(form)
#             redirect('.')

#     def debug_options_submit(self, form):
#         misc.reload_cfg()
#         if not misc.cfg.has_key('debug'):
#             misc.cfg['debug'] = {}
#         for k in ('error_email', 'display_exceptions', 'logger'):
#             misc.cfg['debug'][k] = form.get_widget(k).parse()
#         misc.write_cfg()
#         get_publisher().set_config()


def error_page [html] (error_message):
    html_top(_('Error'))
    '<h1>%s</h1>' % _('Error')
    '<div class="error-page">'
    '<p>%s</p>' % error_message
    '</div>'
