from django import template
from django.conf import settings
from django.template import TemplateSyntaxError

import re

register = template.Library()

@register.inclusion_tag('socialsharing/includes/addthis.html')
def addthis(**kwargs):
    """
    addthis
    =======
    The addthis templatetag will insert the necessary scripts to make use of the 
    [AddThis](https://www.addthis.com) widget.

    Basic usage:
    ------------

        {% addthis %}

    Global settings:
    ----------------
    The only required argument is `pubid`.

    Add a dictionary of properties to your settings.py that will be added to the 
    AddThis Javascript configuration code whenever the templatetag `addthis` is used. 
    These are meant for site-wide configurations.

    `ADDTHIS_PROPERTIES = { 
            'pubid': 'your-pub-id',
            'ui-language': 'pt',
            'etc' : 'yet another value'
    }`

    See the [AddThis Client API](http://www.addthis.com/help/client-api) for 
    information on the available configuration parameters.

    Local (per-template) settings:
    ------------------------------
    The `addthis` templatetag accepts any number of keyword arguments, that 
    will be **specifically** used to generate the `addthis_share` configuration:
    
        {% addthis url="http://www.some-domain.ext/some/path/page.html" description="Some relevant description" %}
    
    See the [AddThis Client API: Sharing Configuration](http://www.addthis.com/help/client-api#configuration-sharing)
    for information on the available sharing configuration parameters.
    
    """
    
    #check for the required pubid
    addthis_config = getattr(settings, 'ADDTHIS_CONFIG', None)
    
    if addthis_config == None:
        raise TemplateSyntaxError('No ADDTHIS_CONFIG found in settings.py.')
    
    if not 'pubid' in addthis_config:
        raise TemplateSyntaxError('The addthis template tag requires a pubid. You set it within ADDTHIS_CONFIG in settings.py.')
    
    #apply some formatting to enable proper javascript values (type-wise)
    for key in addthis_config:
        addthis_config[key] = decorate(addthis_config[key])
    
    #generate keyword arguments js list
    if len(kwargs) > 0:
        addthis_share = kwargs
        
        for key in addthis_share:
            addthis_share[key] = decorate(addthis_share[key])
            
    else:
        addthis_share = None
    
    return { 'addthis': addthis_config, 'addthis_share' : addthis_share }

#helper functions
def decorate(value):
    if isinstance(value, str): return "'%s'" % value
    if isinstance(value, bool): return 'true' if value else 'false'
    
    if re.match(r'^\d+$', value) == None:
        return "'%s'" % value 
    
    return value