try:
    import SOAPpy
except ImportError:
    SOAPpy = None

try:
    import phpserialize
except ImportError:
    phpserialize = None

from django.core.urlresolvers import reverse
from django.db import models
from django.utils.translation import ugettext_lazy as _

from passerelle.base.models import BaseResource
from passerelle.utils.api import endpoint


def phpserialize_loads(s):
    return phpserialize.loads(s.encode('utf-8'))


class Gdc(BaseResource):
    service_url = models.CharField(max_length=128, blank=False,
            verbose_name=_('Service URL'),
            help_text=_('GDC Web Service URL'))

    category = _('Business Process Connectors')

    class Meta:
        verbose_name = _('GDC Web Service')

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

    @endpoint()
    def communes(self, request, *args, **kwargs):
        server = SOAPpy.SOAPProxy(self.service_url)
        soap_result = phpserialize_loads(server.getListeCommune()['listeCommune'])
        result = []
        for k, v in soap_result.items():
            result.append({'id': k, 'text': unicode(v, 'utf-8')})
        result.sort(lambda x,y: cmp(x['id'], y['id']))
        return result

    @endpoint()
    def objets(self, request, *args, **kwargs):
        server = SOAPpy.SOAPProxy(self.service_url)
        soap_result = phpserialize_loads(server.getListeObjet()['listeObjet'])
        result = []
        for k, v in soap_result.items():
            result.append({'id': k, 'text': unicode(v, 'utf-8')})
        result.sort(lambda x,y: cmp(x['id'], y['id']))
        return result
