import datetime
import os.path


from passerelle.utils.jsonresponse import APIError
from passerelle.soap import Soap
from passerelle.xml_builder import XmlBuilder


class ContactEveryoneSoap(Soap):
    WSDL_URL = ('https://www.api-contact-everyone.fr.orange-business.com/'
                'ContactEveryone/services/MultiDiffusionWS?wsdl')
    ORANGE_CERTIFICATE = os.path.join(os.path.dirname(__file__), 'orange.pem')

    url = WSDL_URL

    class ProfileListBuilder(XmlBuilder):
        schema = (
            'PROFILE_LIST',
            ('?loop', 'recipients',
             ('PROFILE',
              ('DEST_NAME', 'name_{to}'),
              ('DEST_FORENAME', 'forename_{to}'),
              ('DEST_ID', 'ID_{to}'),
              ('TERMINAL_GROUP',
               ('TERMINAL',
                ('TERMINAL_NAME', 'mobile1'),
                ('TERMINAL_ADDR', '{to}'),
                ('MEDIA_TYPE_GROUP',
                 ('MEDIA_TYPE', 'sms')))))))
        encoding = 'latin1'

    @property
    def verify(self):
        # Do not break if certificate is not updated
        if datetime.datetime.now() < datetime.datetime(2016, 11, 5):
            return self.ORANGE_CERTIFICATE
        else:
            return False

    def send_message(self, recipients, content):
        try:
            client = self.get_client()
        except Exception as e:
            raise APIError('Orange error: WSDL retrieval failed, %s' % e)
        message = client.factory.create('WSMessage')
        message.fullContenu = True
        message.content = content
        message.subject = content
        message.resumeContent = content
        message.strategy = 'sms'
        send_profiles = self.ProfileListBuilder().string(
            context={'recipients': [{'to': to} for to in recipients]})
        message.sendProfiles = send_profiles
        try:
            resp = client.service.sendMessage(message)
        except Exception as e:
            raise APIError('Orange error: %s' % e)
        else:
            return {'msg_ids': [msg_id for msg_id in resp.msgId]}

    def send_advanced_message(self, recipients, sender, content):
        try:
            client = self.get_client()
        except Exception as e:
            raise APIError('Orange error: WSDL retrieval failed, %s' % e)
        message = client.factory.create('WSAdvancedMessage')
        message.fullContenu = True
        message.content = content
        message.subject = content
        message.resumeContent = content
        message.strategy = 'sms'
        message.smsReplyTo = sender
        send_profiles = self.ProfileListBuilder().string(
            context={'recipients': [{'to': to} for to in recipients]})
        message.sendProfiles = send_profiles
        try:
            resp = client.service.sendAdvancedMessage(message)
        except Exception as e:
            raise APIError('Orange error: %s' % e)
        else:
            return {'msg_ids': [msg_id for msg_id in resp.msgId]}
