import requests
from requests.auth import HTTPBasicAuth

from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.db import models
from django.template import Template, Context
from django.utils.translation import ugettext_lazy as _

from jsonfield import JSONField

from passerelle.base.models import BaseResource


class Pastell(BaseResource):
    url = models.CharField(max_length=128, blank=False,
            verbose_name=_('URL'),
            help_text=_('Pastell URL'))
    verify_cert = models.BooleanField(default=True,
            verbose_name=_('Check HTTPS Certificate validity'))
    username = models.CharField(max_length=128, blank=False,
            verbose_name=_('Username'))
    password = models.CharField(max_length=128, blank=False,
            verbose_name=_('Password'))
    keystore = models.FileField(upload_to='pastell', null=True,
            verbose_name=_('Keystore'),
            help_text=_('Certificate and private key in PEM format'))
    document_type = models.CharField(max_length=128, blank=True,
            verbose_name=_('Document Type'))
    document_fields = JSONField(null=True, verbose_name=_('Fields'))

    category = _('Business Process Connectors')

    class Meta:
        verbose_name = _('Pastell')

    def get_absolute_url(self):
        return reverse('pastell-view', kwargs={'slug': self.slug})

    @classmethod
    def get_add_url(cls):
        return reverse('pastell-add')

    @classmethod
    def get_verbose_name(cls):
        return cls._meta.verbose_name

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

    def pastell_request(self, endpoint, **kwargs):
        if self.keystore:
            kwargs['cert'] = (self.keystore.path, self.keystore.path)
        if not self.verify_cert:
            kwargs['verify'] = False
        kwargs['auth'] = HTTPBasicAuth(self.username, self.password)
        return requests.get(self.url + '/api/' + endpoint, **kwargs).json()

    def get_document_type_choices(self):
        cache_key = 'pastell-%s-document-types' % self.id
        choices = cache.get(cache_key)
        if choices:
            return choices

        document_types = self.pastell_request('document-type.php')

        choices = [(x, document_types.get(x).get('nom')) for x in document_types.keys()]
        cache.set(cache_key, choices, 300)

        return choices

    def get_document_fields(self):
        cache_key = 'pastell-%s-%s-document-fields' % (self.id, self.document_type)
        choices = cache.get(cache_key)
        if choices:
            return choices

        data_dict = {'type': self.document_type}
        fields = self.pastell_request('document-type-info.php', params=data_dict)

        cache.set(cache_key, fields, 300)

        return fields

    def create_document(self, data):
        data_dict = {}
        result = self.pastell_request('list-entite.php', params=data_dict)
        data_dict['id_e'] = result[0].get('id_e') # take first

        data_dict['type'] = self.document_type
        result = self.pastell_request('create-document.php', params=data_dict)
        data_dict['id_d'] = result.get('id_d')

        template_context = Context(data)
        for k, v in (self.document_fields or {}).items():
            template = Template(v)
            data_dict[k] = template.render(template_context)

        self.pastell_request('modif-document.php', params=data_dict)
