import json
import logging
import re

from django.utils.translation import ugettext_lazy as _
from passerelle.utils.api import endpoint
from passerelle.utils.jsonresponse import APIError


class SMSGatewayMixin(object):
    category = _('SMS Providers')

    @classmethod
    def clean_numbers(cls, destinations, default_country_code, prefix='+'):
        numbers = []
        for dest in destinations:
            # most gateways needs the number prefixed by the country code, this is
            # really unfortunate.
            number = ''.join(re.findall('[0-9]', dest))
            if dest.startswith('+'):
                pass  # it already is fully qualified
            elif number.startswith('00'):
                # assumes 00 is international access code, remove it
                number = number[2:]
            elif number.startswith('0'):
                # local prefix, remove 0 and add default country code
                number = default_country_code + number[1:]
            numbers.append(prefix + number)
        return numbers

    @endpoint('json-api', perm='can_send_messages', methods=['post'])
    def send(self, request, *args, **kwargs):
        try:
            data = json.loads(request.body)
            assert isinstance(data, dict), 'JSON payload is not a dict'
            assert 'message' in data, 'missing "message" in JSON payload'
            assert 'from' in data, 'missing "from" in JSON payload'
            assert 'to' in data, 'missing "to" in JSON payload'
            assert isinstance(data['message'], unicode), 'message is not a string'
            assert isinstance(data['from'], unicode), 'from is not a string'
            assert all(map(lambda x: isinstance(x, unicode), data['to'])), \
                'to is not a list of strings'
        except (ValueError, AssertionError) as e:
            raise APIError('Payload error: %s' % e)
        logging.info('sending message %r to %r with sending number %r',
                     data['message'], data['to'], data['from'])
        return self.send_msg(data['message'], data['from'], data['to'])
