from string import Template
from urllib.parse import parse_qs
from urllib.parse import unquote

from ..abstract import AbstractImplementation
from ..error import EInvokationError


AUTOCONFIG_TEMPLATE='''
<?xml version="1.0" encoding="UTF-8"?>
<clientConfig version="1.1">
  <emailProvider id="${domain}">
    <domain>${domain}</domain>
    <incomingServer type="imap">
      <hostname>${hostname}</hostname>
      <port>143</port>
      <socketType>STARTTLS</socketType>
      <authentication>password-cleartext</authentication>
      <username>${mailbox}</username>
    </incomingServer>
    <outgoingServer type="smtp">
      <hostname>${hostname}</hostname>
      <port>587</port>
      <socketType>STARTTLS</socketType>
      <authentication>password-cleartext</authentication>
      <username>${mailbox}</username>
    </outgoingServer>
  </emailProvider>
</clientConfig>
'''


class AutoConfigImplementation(AbstractImplementation):
    contenttype = 'text/xml'
    template = Template(AUTOCONFIG_TEMPLATE)

    def get_email(self, environ):
        query = parse_qs(environ['QUERY_STRING'])
        try:
            return unquote(query['emailaddress'][0]).strip()
        except:
            raise EInvokationError('Invokation Error: An email address argument needs to be speficied.')
