from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from django.http import HttpResponseNotFound
from django.views.generic.base import View, TemplateResponseMixin
from ldt.api.ldt.resources import ProjectResource
from ldt.ldt_utils.models import Project, Content
import logging
from hashcut.models import Mashup, Branding
from django.contrib.auth.models import User

class MashupContextView(View):
    
    branding = "iri"
    
    def get_context_dict(self, request):
        context = {}
        context["branding"] = self.branding
        context["creator"] = ""
        context["nb_mashup_creator"] = ""
        if request and request.user:
            context["creator"] = request.user.username
            if not self.branding or self.branding=="":
                self.branding = "iri"
            brd = Branding.objects.get(name=self.branding)
            context["nb_mashup_creator"] = Mashup.objects.filter(branding=brd,project__owner=request.user).count()
        return context
            
            

class MashupHome(TemplateResponseMixin, MashupContextView):
    
    # iri = default brand name
    branding = "iri"
    template_suffix = "mashup_home.html"
    template_name = "iri_mashup_home.html"
    
    def get_template_names(self):
        """
        Return a list of template names to be used for the request. Must return
        a list. May not be called if get_template is overridden.
        """
        try:
            names = super(MashupHome, self).get_template_names()
        except ImproperlyConfigured:
            raise ImproperlyConfigured("Class MashupHome requires either a definition of 'template_name'")

        # the branding template is supposed to override the default template. So we insert instead of append
        if self.branding and self.branding != "":
            names.insert(0,"%s_%s" % (self.branding, self.template_suffix))
        
        return names
    
    
    def get(self, request, branding="iri", **kwargs):
        self.branding = branding
        brd = Branding.objects.get(name=self.branding)
        m1 = None
        m2 = None
        last_mashups = None
        mashups = Mashup.objects.filter(branding=brd)[:10]
        logging.debug(repr(mashups))
        l = len(mashups)
        if l>0:
            m1 = mashups[0]
        if l>1:
            m2 = mashups[1]
        if l>2:
            last_mashups = mashups[2:]
        context = self.get_context_dict(request)
        context.update({"mashups":last_mashups, "m1":m1, "m2":m2})
        return self.render_to_response(context)
    


class MashupEdit(TemplateResponseMixin, MashupContextView):
    
    # iri = default brand name
    branding = "iri"
    template_suffix = "mashup_edit.html"
    template_name = "iri_mashup_edit.html"
    
    def get_template_names(self):
        """
        Return a list of template names to be used for the request. Must return
        a list. May not be called if get_template is overridden.
        """
        try:
            names = super(MashupEdit, self).get_template_names()
        except ImproperlyConfigured:
            raise ImproperlyConfigured("Class MashupEdit requires either a definition of 'template_name'")

        # the branding template is supposed to override the default template. So we insert instead of append
        if self.branding and self.branding != "":
            names.insert(0,"%s_%s" % (self.branding, self.template_suffix))
        
        return names
    
    def get(self, request, branding="iri", **kwargs):
        self.branding = branding
        context = self.get_context_dict(request)
        return self.render_to_response(context)



# save mashup view, not include in generic views
def save_mashup(request, branding="iri"):
    # First we use the project api to save the project
    proj_api = ProjectResource()
    rtrn = proj_api.dispatch_list(request)
    if rtrn and rtrn['Location']:
        # The api return the api location of the created project (i.e. /a/b/ldt_id/). So we just get the id to get the project object.
        proj_ldt_id = rtrn['Location'].split("/")[-2]
        try:
            proj = Project.objects.get(ldt_id=proj_ldt_id)
        except Project.DoesNotExist:
            raise ObjectDoesNotExist("Save Mashup : project not found. project_ldt_id = " + proj_ldt_id)
        # Now that we have the project object, we can save the mashup object
        brd = Branding.objects.get(name=branding)
        new_mashup = Mashup()
        new_mashup.branding = brd
        new_mashup.project = proj
        new_mashup.save()
    return rtrn
    


class MashupHashcut(TemplateResponseMixin, MashupContextView):
    
    # iri = default brand name
    branding = "iri"
    template_suffix = "mashup_hashcut.html"
    template_name = "iri_mashup_hashcut.html"
    
    def get_template_names(self):
        """
        Return a list of template names to be used for the request. Must return
        a list. May not be called if get_template is overridden.
        """
        try:
            names = super(MashupHashcut, self).get_template_names()
        except ImproperlyConfigured:
            raise ImproperlyConfigured("Class MashupHashcut requires either a definition of 'template_name'")

        # the branding template is supposed to override the default template. So we insert instead of append
        if self.branding and self.branding != "":
            names.insert(0,"%s_%s" % (self.branding, self.template_suffix))
        
        return names
    
    def get(self, request, branding="iri", ldt_id=None, **kwargs):
        self.branding = branding
        if not ldt_id:
            return HttpResponseNotFound("A project id must be given.")
        try:
            proj = Project.objects.get(ldt_id=ldt_id)
        except Project.DoesNotExist:
            raise ObjectDoesNotExist("MashupHashcut : project not found. project_ldt_id = " + ldt_id)
        context = self.get_context_dict(request)
        context.update({"ldt_id":ldt_id, "proj": proj})
        return self.render_to_response(context)
    


class MashupContent(TemplateResponseMixin, MashupContextView):
    
    # iri = default brand name
    branding = "iri"
    template_suffix = "mashup_content.html"
    template_name = "iri_mashup_content.html"
    
    def get_template_names(self):
        """
        Return a list of template names to be used for the request. Must return
        a list. May not be called if get_template is overridden.
        """
        try:
            names = super(MashupContent, self).get_template_names()
        except ImproperlyConfigured:
            raise ImproperlyConfigured("Class MashupContent requires either a definition of 'template_name'")

        # the branding template is supposed to override the default template. So we insert instead of append
        if self.branding and self.branding != "":
            names.insert(0,"%s_%s" % (self.branding, self.template_suffix))
        
        return names
    
    def get(self, request, branding="iri", ctt_id=None, **kwargs):
        self.branding = branding
        if not ctt_id:
            return HttpResponseNotFound("A content id must be given.")
        try:
            content = Content.objects.get(iri_id=ctt_id)
        except Content.DoesNotExist:
            raise ObjectDoesNotExist("MashupContent : content not found. ctt_id = " + ctt_id)
        context = self.get_context_dict(request)
        context.update({"ctt_id":ctt_id, "content": content})
        return self.render_to_response(context)
    


class MashupProfile(TemplateResponseMixin, MashupContextView):
    
    # iri = default brand name
    branding = "iri"
    template_suffix = "mashup_profile.html"
    template_name = "iri_mashup_profile.html"
    
    def get_template_names(self):
        """
        Return a list of template names to be used for the request. Must return
        a list. May not be called if get_template is overridden.
        """
        try:
            names = super(MashupProfile, self).get_template_names()
        except ImproperlyConfigured:
            raise ImproperlyConfigured("Class MashupContent requires either a definition of 'template_name'")

        # the branding template is supposed to override the default template. So we insert instead of append
        if self.branding and self.branding != "":
            names.insert(0,"%s_%s" % (self.branding, self.template_suffix))
        
        return names
    
    def get(self, request, branding="iri", username=None, **kwargs):
        self.branding = branding
        if not username or username=="":
            return HttpResponseNotFound("A username must be given.")
        brd = Branding.objects.get(name=self.branding)
        try:
            user = User.objects.get(username=username)
        except:
            return HttpResponseNotFound("User not found.")
        mashups = Mashup.objects.filter(branding=brd, project__owner=user)
        
        context = self.get_context_dict(request)
        context.update({"username":username, "mashups":mashups})
        return self.render_to_response(context)
    
    
    