import requests
from django.db import models
from django.utils.encoding import force_str
from django.utils.translation import gettext_lazy as _

from passerelle.sms.models import SMSResource
from passerelle.utils.jsonresponse import APIError


class OxydSMSGateway(SMSResource):
    username = models.CharField(verbose_name=_('Username'), max_length=64)
    password = models.CharField(verbose_name=_('Password'), max_length=64)

    TEST_DEFAULTS = {
        'create_kwargs': {
            'username': 'john',
            'password': 'doe',
        },
        'test_vectors': [
            {
                'response': '',
                'result': {
                    'err': 1,
                    'err_desc': 'OXYD error: some destinations failed',
                    'data': [
                        ['0033688888888', "OXYD error: response is not 200"],
                        ['0033677777777', "OXYD error: response is not 200"],
                    ],
                },
            },
            {
                'response': '200',
                'result': {
                    'err': 0,
                    'data': None,
                },
            },
        ],
    }
    URL = 'http://sms.oxyd.fr/send.php'

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

    def send_msg(self, text, sender, destinations, **kwargs):
        """Send a SMS using the Oxyd provider"""

        results = []
        for dest in destinations:
            params = {
                'id': self.username,
                'pass': self.password,
                'num': dest,
                'sms': text.encode('utf-8'),
                'flash': '0',
            }
            try:
                r = self.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 force_str(code) != '200':
                    results.append('OXYD error: response is not 200')
                else:
                    results.append(0)
        if any(results):
            raise APIError('OXYD error: some destinations failed', data=list(zip(destinations, results)))
        # credit consumed is unknown

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

    def get_money_left(self):
        raise NotImplementedError
