# Path: helpers/sessions.py
# class SessionHandler(RequestHandler):
# 
#     # Override dispatch method to get and save session data with every request
#     def dispatch(self):
#         self.session_store = get_store(request=self.request)
#         try:
#             RequestHandler.dispatch(self)
#         finally:
#             self.session_store.save_sessions(self.response)
# 
#     # Make session data available within handlers
#     @cached_property
#     def session(self):
#         return self.session_store.get_session()
# 
#     def current_user(self, user=None):
#         if user:
#             self.session['current_user'] = user.google_id
# 
#         if 'current_user' in self.session:
#             return User.get_by_google_id(self.session['current_user'])
#         else:
#             return None
# 
# Path: helpers/views.py
# def static(file_path):
#     file_path = os.path.join(os.path.abspath('./static'), file_path)
#     return open(file_path, 'r').read()
# 
# 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_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)


import logging
from helpers.sessions import SessionHandler
from helpers.views import static, render
from models.data_source import DataSource
# -*- coding: utf-8 -*-
#
# Base routes and error handlers
#

class HomeRoute(SessionHandler):

    def get(self):
        data = {}
        data['current_user'] = self.current_user().to_dict() if self.current_user() else {}
        data['featured_data']  = [ds.to_dict() for ds in DataSource.get_featured(limit=5)]
        body = render('index.html', data)
        self.response.write(body)


def error_404(request, response, exception):
    msg_info = (request.method, request.path_url, request.POST.items(), exception)
    logging.error("%s %s %s 404 '%s'" % msg_info)
    response.write(render('404.html'))
    response.set_status(404)


def error_500(request, response, exception):
    msg_info = (request.method, request.path_url, request.POST.items(), exception, exception.__class__)
    logging.error("%s %s %s 500 '%s' %s" % msg_info)

# Path: helpers/sessions.py
# class SessionHandler(RequestHandler):
# 
#     # Override dispatch method to get and save session data with every request
#     def dispatch(self):
#         self.session_store = get_store(request=self.request)
#         try:
#             RequestHandler.dispatch(self)
#         finally:
#             self.session_store.save_sessions(self.response)
# 
#     # Make session data available within handlers
#     @cached_property
#     def session(self):
#         return self.session_store.get_session()
# 
#     def current_user(self, user=None):
#         if user:
#             self.session['current_user'] = user.google_id
# 
#         if 'current_user' in self.session:
#             return User.get_by_google_id(self.session['current_user'])
#         else:
#             return None
# 
# Path: helpers/views.py
# def static(file_path):
#     file_path = os.path.join(os.path.abspath('./static'), file_path)
#     return open(file_path, 'r').read()
# 
# 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_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: controllers/root.py
import logging
from helpers.sessions import SessionHandler
from helpers.views import static, render
from models.data_source import DataSource

# -*- coding: utf-8 -*-
#
# Base routes and error handlers
#

class HomeRoute(SessionHandler):

    def get(self):
        data = {}
        data['current_user'] = self.current_user().to_dict() if self.current_user() else {}
        data['featured_data']  = [ds.to_dict() for ds in DataSource.get_featured(limit=5)]
        body = render('index.html', data)
        self.response.write(body)


def error_404(request, response, exception):
    msg_info = (request.method, request.path_url, request.POST.items(), exception)
    logging.error("%s %s %s 404 '%s'" % msg_info)
    response.write(render('404.html'))
    response.set_status(404)


def error_500(request, response, exception):
    msg_info = (request.method, request.path_url, request.POST.items(), exception, exception.__class__)
    logging.error("%s %s %s 500 '%s' %s" % msg_info)

    response.write(render('500.html'))