import json

from mako.template import Template
from mako.lookup import TemplateLookup
from mako.exceptions import TopLevelLookupException

from django.conf import settings
from django.db import models

from passerelle.repost.models import BaseRepost


class BaseMakoRepost(BaseRepost):

    def get_input_template(self):
        return None

    def get_output_template(self):
        return None

    def repost(self, data, **kwargs):
        input_template = self.get_input_template()
        if input_template:
            input_json = input_template.render_unicode(data=data, args=kwargs)
            data = json.loads(input_json)

        out_data = BaseRepost.repost(self, data, **kwargs)

        output_template = self.get_output_template()
        if output_template:
            output_json = output_template.render_unicode(data=out_data, args=kwargs)
            out_data = json.loads(output_json)
        return out_data

    class Meta:
        abstract = True


class MakoPrototypeRepost(BaseMakoRepost):
    input_template = models.TextField(blank=True)
    output_template = models.TextField(blank=True)

    parameters = '*'

    def get_input_template(self):
        if self.input_template:
            return Template(self.input_template)
        return None

    def get_output_template(self):
        if self.output_template:
            return Template(self.output_template)
        return None



template_lookup = TemplateLookup(directories=settings.MAKO_TEMPLATES_DIRS,
        module_directory=settings.MAKO_TEMPLATES_MODULES)

class MakoRepost(BaseMakoRepost):

    parameters = '*'

    def get_input_template(self):
        try:
            return template_lookup.get_template(self.slug + '-input.mako')
        except TopLevelLookupException:
            return None

    def get_output_template(self):
        try:
            return template_lookup.get_template(self.slug + '-output.mako')
        except TopLevelLookupException:
            return None

