import requests

from django.db import models

from passerelle.utils.jsonresponse import APIError
from passerelle.base.models import BaseResource
from passerelle.sms import SMSGatewayMixin


class OxydSMSGateway(BaseResource, SMSGatewayMixin):
    username = models.CharField(max_length=64)
    password = models.CharField(max_length=64)
    default_country_code = models.CharField(max_length=3, default=u'33')
    # FIXME: add regexp field, to check destination and from format

    manager_view_template_name = 'passerelle/manage/messages_service_view.html'

    TEST_DEFAULTS = {
        'create_kwargs': {
            'username': 'john',
            'password': 'doe',
        },
        'test_vectors': [
            {
                'response': '',
                'result': {
                    'err': 1,
                    'err_desc': 'OXYD error: some destinations failed',
                    'data': [
                        ['33688888888', "OXYD error: received content '' instead of 200"],
                        ['33677777777', "OXYD error: received content '' instead of 200"],
                    ],
                }
            },
            {
                'response': '200',
                'result': {
                    'err': 0,
                    'data': None,
                }
            }
        ],
    }
    URL = 'http://sms.oxyd.fr/send.php'

    class Meta:
        verbose_name = 'Oxyd'
        db_table = 'sms_oxyd'

    @classmethod
    def get_icon_class(cls):
        return 'phone'

    def send_msg(self, text, sender, destinations):
        """Send a SMS using the Oxyd provider"""
        # unfortunately it lacks a batch API...
        destinations = self.clean_numbers(destinations, self.default_country_code, prefix='')
        results = []
        for dest in destinations:
            params = {
                'id': self.username,
                'pass': self.password,
                'num': dest,
                'sms': text.encode('utf-8'),
                'flash': '0',
            }
            try:
                r = requests.post(self.URL, params)
            except requests.RequestException as e:
                results.append('OXYD error: POST failed, %s' % e)
            else:
                code = r.content and r.content.split()[0]
                if code != '200':
                    results.append('OXYD error: received content %r instead of 200' % r.content)
                else:
                    results.append(0)
        if any(results):
            raise APIError('OXYD error: some destinations failed', data=zip(destinations, results))
        return None

    def get_sms_left(self, type='standard'):
        raise NotImplementedError

    def get_money_left(self):
        raise NotImplementedError
