from tastypie import fields
from tastypie.resources import ModelResource, Resource, ALL, Bundle
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from tastypie.serializers import Serializer
from snappybouncer.models import Conversation, UserAccount, Ticket
from snappybouncer.tasks import (send_helpdesk_response,
                                 send_helpdesk_response_jembi)
import logging
import json
import re
import urlparse
from HTMLParser import HTMLParser
from django.core.exceptions import ObjectDoesNotExist
from django.conf.urls import url

logger = logging.getLogger(__name__)

# ModelResource access using standard format


class UserAccountResource(ModelResource):

    class Meta:
        queryset = UserAccount.objects.all()
        resource_name = 'useraccount'
        list_allowed_methods = ['get']
        include_resource_uri = True
        always_return_data = True
        authentication = ApiKeyAuthentication()
        authorization = Authorization()
        filtering = {
            'key': ALL,
        }


class ConversationResource(ModelResource):
    user_account = fields.ToOneField(UserAccountResource, 'user_account')

    class Meta:
        queryset = Conversation.objects.all()
        resource_name = 'conversation'
        list_allowed_methods = ['get']
        include_resource_uri = True
        always_return_data = True
        authentication = ApiKeyAuthentication()
        authorization = Authorization()
        filtering = {
            'key': ALL,
            'user_account': ALL
        }

    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/key/(?P<key>[\w\d_.-]+)/$" %
                self._meta.resource_name,
                self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
        ]


class TicketResource(ModelResource):
    conversation = fields.ToOneField(ConversationResource, 'conversation')

    class Meta:
        queryset = Ticket.objects.all()
        resource_name = 'ticket'
        list_allowed_methods = ['get', 'post']
        include_resource_uri = True
        always_return_data = True
        authentication = ApiKeyAuthentication()
        authorization = Authorization()
        filtering = {
            'contact_key': ALL,
            'msisdn': ALL,