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

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


class MobytSMSGateway(SMSResource):
    URL = 'http://multilevel.mobyt.fr/sms/batch.php'
    MESSAGES_QUALITIES = (
        ('l', _('sms direct')),
        ('ll', _('sms low-cost')),
        ('n', _('sms top')),
    )
    username = models.CharField(verbose_name=_('Username'), max_length=64)
    password = models.CharField(verbose_name=_('Password'), max_length=64)
    quality = models.CharField(
        max_length=4, choices=MESSAGES_QUALITIES, default='l', verbose_name=_('Message quality')
    )

    TEST_DEFAULTS = {
        'create_kwargs': {
            'username': 'john',
            'password': 'doe',
        },
        'test_vectors': [
            {
                'response': '',
                'result': {
                    'err': 1,
                    'err_desc': 'MobyT error: response is not "OK"',
                },
            }
        ],
    }

    class Meta:
        verbose_name = 'Mobyt'
        db_table = 'sms_mobyt'

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

        rcpt = ','.join(destinations)
        params = {
            'user': self.username,
            'pass': self.password,
            'rcpt': rcpt,
            'data': text,
            'sender': sender,
            'qty': self.quality,
        }
        try:
            r = self.requests.post(self.URL, data=params)
        except requests.RequestException as e:
            raise APIError('MobyT error: POST failed, %s' % e)
        if r.text[:2] != "OK":
            raise APIError('MobyT error: response is not "OK"')
        # credit consumed is unknown
