from string import Template
from xml.dom.minidom import parseString

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


AUTODISCOVER_TEMPLATE='''
<?xml version="1.0" encoding="utf-8" ?>
<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/responseschema/2006">
  <Response xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a">
    <Account>
      <AccountType>email</AccountType>
      <Action>settings</Action>
      <Protocol>
        <Type>IMAP</Type>
        <Server>${hostname}</Server>
        <Port>143</Port>
        <DomainRequired>off</DomainRequired>
        <SPA>off</SPA>
        <Encryption>TLS</Encryption>
        <AuthRequired>on</AuthRequired>
        <LoginName>${mailbox}</LoginName>
      </Protocol>
      <Protocol>
        <Type>SMTP</Type>
        <Server>${hostname}</Server>
        <Port>587</Port>
        <DomainRequired>off</DomainRequired>
        <SPA>off</SPA>
        <Encryption>TLS</Encryption>
        <AuthRequired>on</AuthRequired>
        <UsePOPAuth>off</UsePOPAuth>
        <SMTPLast>off</SMTPLast>
        <LoginName>${mailbox}</LoginName>
      </Protocol>
    </Account>
  </Response>
</Autodiscover>
'''

class AutoDiscoverImplementation(AbstractImplementation):
    contenttype = 'text/xml'
    template = Template(AUTODISCOVER_TEMPLATE)

    def get_email(self, environ):
        length = int(environ.get('CONTENT_LENGTH', 0))
        data = environ['wsgi.input'].read(length)
        try:
            xml = parseString(data)
        except:
            raise EInvokationError('Invalid XML data provided.')
        try:
            node = xml.getElementsByTagName('EMailAddress')[0]
            return node.firstChild.nodeValue.strip()
        except:
            raise EInvokationError('Invokation Error: An email address element needs to be speficied.')
