import json
import logging

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

import requests

from passerelle.base.models import BaseResource


def get_default_welco_url():
    '''Get default welco URL from a setting than can be set in a Publik
       setting.
    '''
    return getattr(settings, 'PASSERELLE_DEFAULT_WELCO_URL', '')


class PBXMixin(BaseResource):
    welco_url = models.URLField(
        verbose_name=_('welco URL'),
        default=get_default_welco_url,
        max_length=120)

    category = _('Telephony')

    def notify_welco(self, event, caller, callee, data=None):
        assert event in ('start', 'stop')
        assert isinstance(caller, basestring)
        assert isinstance(callee, basestring)
        assert not data or isinstance(data, dict)
        logger = logging.getLogger(__name__)
        caller = unicode(caller)
        callee = unicode(callee)
        event = unicode(event)

        payload = {
            'event': event,
            'caller': caller,
            'callee': callee,
        }
        if data:
            payload['data'] = data
        requests.post(self.welco_url, data=json.dumps(payload),
                      headers={'content-type': 'application/json'})
        logger.info(u'notified welco of event %s from %s to %s',
                    event, caller, callee)

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

    class Meta:
        abstract = True
