# -*- coding: utf-8 -*-
#
# Copyright (c) 2011,2012 RMIT e-Research Office
#   (RMIT University, Australia)
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#    *  Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#    *  Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#    *  Neither the name of RMIT University nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
"""
.. module:: extras
   :synopsis: Template tags for templates 

.. moduleauthor:: Ian Thomas <Ian.Edward.Thomas@rmit.edu.au>


"""

from django.template import Library
from django import template

# TODO:unfortunately, custom tags can only take one parameter

def dictSQinclabeltag(d, key):
    
    return d["SQ/" + key+"/INC"].label_tag()

def dictSQdellabeltag(d, key):
    
    return d["SQ/" + key+"/DEL"].label_tag()


def dictSQdelfield(d, key):
    return d["SQ/" + key+"/DEL"]

def dictSQincfield(d, key):
    return d["SQ/" + key+"/INC"]


def dictSRinclabeltag(d, key):
    
    return d["SR/" + key+"/INC"].label_tag()

def dictSRnotlabeltag(d, key):
    
    return d["SR/" + key+"/NOT"].label_tag()


def dictSRnotfield(d, key):
    return d["SR/" + key+"/NOT"]

def dictSRincfield(d, key):
    return d["SR/" + key+"/INC"]


def dictVClabeltag(d, key):
    return d["VC/" + key].label_tag()


def dictVCfield(d, key):
    return d["VC/" + key]


def fieldlookup(d,key):
    return d[key]


def labellookup(d,key):
    return d[key].label_tag()


from smra.smra_portal.models import VirtualCollectionParameter

# TODO: should handle parameters in context of schemas
def paramval(virt,name):
    try:                              
        param = VirtualCollectionParameter.objects.get(paramset__virt__pk=virt.pk,
                                                       name__name=name,
                                                       paramset__virt__public=True)
        # Check for public just to be extra sure
        return param.value    
    except VirtualCollectionParameter.DoesNotExist:
        return ""


# TODO: should handle parameters in context of schemas
def paramexists(virt,name):
    try:                              
        param = VirtualCollectionParameter.objects.get(paramset__virt__pk=virt.pk,
                                                       name__name=name,
                                                       paramset__virt__public=True)
        # Check for public just to be extra sure
        
    except VirtualCollectionParameter.DoesNotExist:
        return False
    
    return param.value
      
    
from smra.smra_portal.models import Schema
from smra.smra_portal.models import VirtualCollectionParameterSet
from smra.smra_portal.models import VirtualCollectionParameter

def partyinfo(virt,name):
    namespace = "http://rmit.edu.au/rif-cs/party/1.0/"
    try:
        schema = Schema.objects.get(
            namespace__exact=namespace)
    except Schema.DoesNotExist:
        return [("noschema","noschema")]
    
    try:
        parametersets = \
             VirtualCollectionParameterSet.objects.filter(\
                                schema=schema,
                                virt=virt)

    except VirtualCollectionParameterSet.DoesNotExist, e:
        return [("noparamset","noparamset")]
     
    res = []
    for ps in parametersets:
         
        try:
            params = VirtualCollectionParameter.objects.filter(
                                                       paramset = ps,
                                                       paramset__virt=virt)
        except VirtualCollectionParameter.DoesNotExist, e:
            return []
            
            
        pres = ["UnknownParty","UnknownRelation"]     
        for p in params:
            if p.name.name=='party_id':
                pres[0] = p.value
            if p.name.name =='relationtocollection_id':
                pres[1] = p.value
        res.append(pres)
            
             
    return res
     
        
        
from smra.smra_portal.models import PartyRecord

register = template.Library()

def truncate(value, arg):
    """
    Truncates a string after a given number of chars  
    Argument: Number of chars to truncate after
    """
    try:
        length = int(arg)
    except ValueError: # invalid literal for int()
        return value # Fail silently.
    if not isinstance(value, basestring):
        value = str(value)
    if (len(value) > length):
        return value[:length] + "..."
    else:
        return value
    
    
register = template.Library()
#register.filter('dictSQinclabeltag', dictSQinclabeltag)
#register.filter('dictSQdellabeltag', dictSQdellabeltag)
#register.filter('dictSQdelfield', dictSQdelfield)
#register.filter('dictSQincfield', dictSQincfield)
#register.filter('dictSRinclabeltag', dictSRinclabeltag)
#register.filter('dictSRnotlabeltag', dictSRnotlabeltag)
#register.filter('dictSRnotfield', dictSRnotfield)
#register.filter('dictSRincfield', dictSRincfield)
register.filter('truncate', truncate)
#register.filter('dictVClabeltag', dictVClabeltag)
#register.filter('dictVCfield', dictVCfield)
register.filter('fieldlookup',fieldlookup)
register.filter('labellookup',labellookup)
register.filter('paramval',paramval)
register.filter('paramexists',paramexists)
register.filter('partyinfo',partyinfo)