# Path: models/data_source.py
# class DataSource(db.Model):
# 
#     # Properties
#     created_at         = db.DateTimeProperty(required=True)
#     description        = db.TextProperty(default=u'')
#     google_spreadsheet = db.StringProperty(required=True)
#     google_worksheet   = db.StringProperty(required=True)
#     is_featured        = db.BooleanProperty(default=False)
#     licence            = db.TextProperty(default=u'')
#     modified_at        = db.DateTimeProperty(required=True)
#     slug               = db.StringProperty(required=True)
#     tags               = db.StringProperty(default=u'')
#     tbl_stars          = db.IntegerProperty(default=0)
#     title              = db.StringProperty(default=u'')
#     user               = db.ReferenceProperty(User, collection_name="data_sources")
# 
#     def fetch_data_views(self):
#         return self.data_views.order('-modified_at').fetch(limit=None)
# 
#     def to_dict(self):
#         return {
#             'created_at':         self.created_at.strftime('%Y-%m-%d %H:%M:%s'),
#             'data_views':         [dv.to_dict() for dv in self.fetch_data_views()],
#             'description':        self.description,
#             'google_spreadsheet': self.google_spreadsheet,
#             'google_worksheet':   self.google_worksheet,
#             'id':                 self.key().id(),
#             'is_featured':        self.is_featured,
#             'licence':            self.licence,
#             'modified_at':        self.modified_at.strftime('%Y-%m-%d %H:%M:%s'),
#             'slug':               self.slug,
#             'tags':               self.tags.split(','),
#             'tbl_stars':          self.tbl_stars,
#             'title':              self.title,
#             'used_extensions':    self.used_extensions(),
#             'user_id':            self.user.key().id(),
#             'user_profile_name':  self.user.profile_name,
#             'user_profile_slug':  self.user.profile_slug,
#             'public_url':         self.public_url(),
#             'spreadsheet_url':    self.spreadsheet_url(),
#         }
# 
#     def public_url(self):
#         return "/%s/%s/" % (self.user.profile_slug, self.slug)
# 
#     def spreadsheet_url(self):
#         return "https://docs.google.com/spreadsheet/ccc?key=%s" % self.google_spreadsheet
# 
#     def used_extensions(self):
#         """A list of the extensions already in use by the data views of this data source"""
#         return [dv.extension for dv in self.fetch_data_views()]
# 
#     def get_data(self, limit=None):
#         """Fetch worksheet data from Google"""
#         return google_api.get_cell_data(self.user.credentials, self.google_spreadsheet, self.google_worksheet, limit=limit)
# 
#     @classmethod
#     def get_by_slug(self, user, slug):
#         """ Find a data source, belonging to the user, with the specified profile slug """
#         return user.data_sources.filter('slug =', slug).get()
# 
#     @classmethod
#     def get_featured(self, limit=10):
#         """Get data sources flagged as featured"""
#         return DataSource.gql("WHERE is_featured = TRUE ORDER BY created_at DESC").fetch(limit=limit)
# 
# Path: helpers/views.py
# def render_data(template, data={}):
#     try:
#         return DATA_RENDER.from_string(template).render(data)
# 
#     # TODO Consider allow execptions to surface to the request handler for issue#31
# 
#     except jinja2.exceptions.TemplateSyntaxError as e:
#         logging.error("TEMPLATE\n%s" % template)
#         logging.error("DATA\n%s" % data)
#         logging.error("ERROR <%s> line %s, %s" % (e.__class__, e.lineno, e.message))
#         return "Syntax error in template [line %s] %s" % (e.lineno, e.message)
# 
#     except jinja2.exceptions.TemplateError as e:
#         logging.error("TEMPLATE\n%s" % template)
#         logging.error("DATA\n%s" % data)
#         logging.error("ERROR <%s> %s" % (e.__class__, e))
#         return "Error in template - %s" % e
# 
#     except Exception as e:
#         logging.error("TEMPLATE %s" % template)
#         logging.error("DATA %s" % data)
#         logging.error("ERROR <%s> %s" % (e.__class__, e))
#         # Is this dangerous?
#         return "Error in template - %s" % e
# 
# def render(template_file, template_data={}, ):
#     template = APP_RENDER.get_template(template_file)
#     template_data['VERSION'] = main.__version__
#     return template.render(template_data)


import logging
from google.appengine.ext import db
from models.data_source import DataSource
from helpers.views import render_data, render
            'download_url': self.download_url(),
            'extension':    self.extension,
            'filetype':     self.filetype,
            'id':           self.key().id(),
            'mimetype':     self.mimetype,
            'modified_at':  self.modified_at.strftime('%Y-%m-%d %H:%M:%s'),
            'source_id':    self.data_source.key().id(),
            'template':     self.template,
        }

        if default_template:
            data['data_preview']     = self.data_source.get_data(limit=5)
            data['default_template'] = self.default_template(data['data_preview'])
            # Use the default template, if one is not already set
            if not data['template']:
                data['template'] = data['default_template'] 

        return data

    def download_url(self):
        return "/%s/%s.%s" % (self.data_source.user.profile_slug, self.data_source.slug, self.extension)

    def render(self, limit=None):
        data     = self.data_source.get_data(limit=limit)
        template = self.template
        return render_data(template, data)

    def default_template(self, source_data):
        """Return a generated default template for this view type"""
        try: 

# Path: models/data_source.py
# class DataSource(db.Model):
# 
#     # Properties
#     created_at         = db.DateTimeProperty(required=True)
#     description        = db.TextProperty(default=u'')
#     google_spreadsheet = db.StringProperty(required=True)
#     google_worksheet   = db.StringProperty(required=True)
#     is_featured        = db.BooleanProperty(default=False)
#     licence            = db.TextProperty(default=u'')
#     modified_at        = db.DateTimeProperty(required=True)
#     slug               = db.StringProperty(required=True)
#     tags               = db.StringProperty(default=u'')
#     tbl_stars          = db.IntegerProperty(default=0)
#     title              = db.StringProperty(default=u'')
#     user               = db.ReferenceProperty(User, collection_name="data_sources")
# 
#     def fetch_data_views(self):
#         return self.data_views.order('-modified_at').fetch(limit=None)
# 
#     def to_dict(self):
#         return {
#             'created_at':         self.created_at.strftime('%Y-%m-%d %H:%M:%s'),
#             'data_views':         [dv.to_dict() for dv in self.fetch_data_views()],
#             'description':        self.description,
#             'google_spreadsheet': self.google_spreadsheet,
#             'google_worksheet':   self.google_worksheet,
#             'id':                 self.key().id(),
#             'is_featured':        self.is_featured,
#             'licence':            self.licence,
#             'modified_at':        self.modified_at.strftime('%Y-%m-%d %H:%M:%s'),
#             'slug':               self.slug,
#             'tags':               self.tags.split(','),
#             'tbl_stars':          self.tbl_stars,
#             'title':              self.title,
#             'used_extensions':    self.used_extensions(),
#             'user_id':            self.user.key().id(),
#             'user_profile_name':  self.user.profile_name,
#             'user_profile_slug':  self.user.profile_slug,
#             'public_url':         self.public_url(),
#             'spreadsheet_url':    self.spreadsheet_url(),
#         }
# 
#     def public_url(self):
#         return "/%s/%s/" % (self.user.profile_slug, self.slug)
# 
#     def spreadsheet_url(self):
#         return "https://docs.google.com/spreadsheet/ccc?key=%s" % self.google_spreadsheet
# 
#     def used_extensions(self):
#         """A list of the extensions already in use by the data views of this data source"""
#         return [dv.extension for dv in self.fetch_data_views()]
# 
#     def get_data(self, limit=None):
#         """Fetch worksheet data from Google"""
#         return google_api.get_cell_data(self.user.credentials, self.google_spreadsheet, self.google_worksheet, limit=limit)
# 
#     @classmethod
#     def get_by_slug(self, user, slug):
#         """ Find a data source, belonging to the user, with the specified profile slug """
#         return user.data_sources.filter('slug =', slug).get()
# 
#     @classmethod
#     def get_featured(self, limit=10):
#         """Get data sources flagged as featured"""
#         return DataSource.gql("WHERE is_featured = TRUE ORDER BY created_at DESC").fetch(limit=limit)
# 
# Path: helpers/views.py
# def render_data(template, data={}):
#     try:
#         return DATA_RENDER.from_string(template).render(data)
# 
#     # TODO Consider allow execptions to surface to the request handler for issue#31
# 
#     except jinja2.exceptions.TemplateSyntaxError as e:
#         logging.error("TEMPLATE\n%s" % template)
#         logging.error("DATA\n%s" % data)
#         logging.error("ERROR <%s> line %s, %s" % (e.__class__, e.lineno, e.message))
#         return "Syntax error in template [line %s] %s" % (e.lineno, e.message)
# 
#     except jinja2.exceptions.TemplateError as e:
#         logging.error("TEMPLATE\n%s" % template)
#         logging.error("DATA\n%s" % data)
#         logging.error("ERROR <%s> %s" % (e.__class__, e))
#         return "Error in template - %s" % e
# 
#     except Exception as e:
#         logging.error("TEMPLATE %s" % template)
#         logging.error("DATA %s" % data)
#         logging.error("ERROR <%s> %s" % (e.__class__, e))
#         # Is this dangerous?
#         return "Error in template - %s" % e
# 
# def render(template_file, template_data={}, ):
#     template = APP_RENDER.get_template(template_file)
#     template_data['VERSION'] = main.__version__
#     return template.render(template_data)


# Path: models/data_view.py
import logging
from google.appengine.ext import db
from models.data_source import DataSource
from helpers.views import render_data, render

            'download_url': self.download_url(),
            'extension':    self.extension,
            'filetype':     self.filetype,
            'id':           self.key().id(),
            'mimetype':     self.mimetype,
            'modified_at':  self.modified_at.strftime('%Y-%m-%d %H:%M:%s'),
            'source_id':    self.data_source.key().id(),
            'template':     self.template,
        }

        if default_template:
            data['data_preview']     = self.data_source.get_data(limit=5)
            data['default_template'] = self.default_template(data['data_preview'])
            # Use the default template, if one is not already set
            if not data['template']:
                data['template'] = data['default_template'] 

        return data

    def download_url(self):
        return "/%s/%s.%s" % (self.data_source.user.profile_slug, self.data_source.slug, self.extension)

    def render(self, limit=None):
        data     = self.data_source.get_data(limit=limit)
        template = self.template
        return render_data(template, data)

    def default_template(self, source_data):
        """Return a generated default template for this view type"""
        try: 

            return render('default_template.%s' % self.extension, source_data)