from django.utils.translation import ugettext_lazy as _
from django.db import models

import requests

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


class MobytSMSGateway(BaseResource, SMSGatewayMixin):
    URL = 'http://multilevel.mobyt.fr/sms/batch.php'
    MESSAGES_QUALITIES = (
        ('l', _('sms direct')),
        ('ll', _('sms low-cost')),
        ('n', _('sms top')),
    )
    username = models.CharField(max_length=64)
    password = models.CharField(max_length=64)
    quality = models.CharField(max_length=4, choices=MESSAGES_QUALITIES, default='l',
                               verbose_name=_('message quality'))
    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': 'MobyT error: received \'\' instead of OK',
                }
            }

        ],

    }

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

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

    def send_msg(self, text, sender, destinations):
        """Send a SMS using the Mobyt provider"""
        # unfortunately it lacks a batch API...
        destinations = self.clean_numbers(destinations, self.default_country_code)
        rcpt = ','.join(destinations)
        params = {
            'user': self.username,
            'pass': self.password,
            'rcpt': rcpt,
            'data': text,
            'sender': sender,
            'qty': self.quality,
        }
        try:
            r = requests.post(self.URL, data=params)
        except requests.RequestException, e:
            raise APIError('MobyT error: POST failed, %s' % e)
        if r.content[:2] != "OK":
            raise APIError('MobyT error: received %r instead of OK' % r.content)
        return None
