import logging
import urllib
import urllib2
import json

from django.conf import settings
import django_journal

logger = logging.getLogger(__name__)

class OVHSMSCarrier(object):
    URL = 'https://www.ovh.com/cgi-bin/sms/http2sms.cgi'
    SMS_CLASS = 1

    def send_sms(self, to, message, sms_class=None):
        payload = unicode(message).encode('utf-8')
        sms_class = sms_class or self.SMS_CLASS
        to = ','.join(to)
        params = {
          'account': settings.OVH_SMS_ACCOUNT,
          'login': settings.OVH_SMS_LOGIN,
          'password': settings.OVH_SMS_PASSWORD,
          'from': settings.OVH_SMS_FROM,
          'to': to,
          'message': payload,
          'contentType': 'text/json',
          'class': sms_class,
        }
        django_journal.error_record('ovh-sms',
                'OVH SMS CARRIER: sending message {message} to {numbers}',
                message=message, numbers=to)
        stream = urllib2.urlopen('%s?%s' % (self.URL, urllib.urlencode(params)))
        result = json.loads(stream.read())
        if 100 <= result['status'] < 200:
            credit_alert = getattr(settings, 'OVH_SMS_CREDIT_ALERT', 100)
            credit_left = result['creditLeft']
            if credit_left < credit_alert:
                django_journal.error_record('error', 'OVH SMS CARRIER: credit '
                        'left({credit_left}) < credit alert limit({credit_alert})',
                        credit_left=credit_left, credit_alert=credit_alert)
        else:
            django_journal.error_record('error', 'OVH SMS CARRIER: status "{status}"'
                    'message "{message}"', **result)
