import os
import webapp2
import jinja2
import json

from backend.util import security
from backend.util import cookies, datetime_format
from backend.model.user import User
import modules

toplevel_dir = os.path.join(os.path.dirname(__file__), '../../')

class BaseHandler(webapp2.RequestHandler):
    def __init__(self, request, response, module=modules.none):
        super(BaseHandler, self).__init__(request, response)
        self.module = module
        self.templates_environment = BaseHandler.template_environment_for_module(module)
        self.templates_environment.filters['date_month_human'] = datetime_format.as_month_date_human
        self.templates_environment.filters['date_month'] = datetime_format.as_month_date

        uid = self.read_secure_cookie(cookies.Names.user_id)
        self.user = uid and User.get_by_id(long(uid))

    @classmethod
    def templates_dir_for_module(this_class, module):
        return os.path.join(toplevel_dir, 'frontend', module.name, 'html')

    @classmethod
    def template_environment_for_module(this_class, module):
        locations = []
        locations.append(BaseHandler.templates_dir_for_module(modules.common))
        if module:
            locations.append(BaseHandler.templates_dir_for_module(module))
        return jinja2.Environment(
            loader = jinja2.FileSystemLoader(locations),
            autoescape = True)

    def get(self, *args):
        if self.user:
            if not self.user.activated and self.module.name != modules.profile.name:
                self.redirect(modules.profile.url)
            else:
                self.authenticated_get(*args)
        else:
            self.redirect(modules.login.url)

    def post(self, *args):
        if self.user:
            self.authenticated_post(*args)
        else:
            self.redirect(modules.login.url)

    def delete(self, *args):
        if self.user:
            self.authenticated_delete(*args)
        else:
            self.redirect(modules.login.url)

    def get_template(self, name):
        return self.templates_environment.get_template(name)
        
    def read_secure_cookie(self, name):
        cookie_value = self.request.cookies.get(name)
        return cookie_value and security.check_secure_value(cookie_value)
    
    def is_localhost(self):
        import re
        return re.match(r'localhost', self.request.headers.get('Host'), re.IGNORECASE) != None
        
    def set_secure_cookie(self, name, value):
        cookie_value = security.make_secure_value(value)
        domain_option = 'Domain=.lomas-naucalpan.info' if not self.is_localhost() else ''
        self.add_header(
            'Set-Cookie',
            '%s=%s; Path=/; %s' % (name, cookie_value, domain_option))

    def add_header(self, name, value):
        self.response.headers.add_header(name, value)

    def write(self, *args, **keywords):
        self.response.out.write(*args, **keywords)
        
    def render(self, template_name, **params):
        template = self.get_template(template_name)
        if self.user:
            params.update({'user' : self.user})
        self.write(template.render(params))
        
    def extract_request_parameters(self, *names):
        params = {}
        for name in names:
            params[name] = self.request.get(name).strip()
        return params

    def has_parameter(self, name):
        return self.request.get(name) != ''

    def on_admin(self, this, otherwise=None):
        if self.user.is_admin():
            this()
        else:
            if not otherwise:
                otherwise = lambda: self.redirect(modules.welcome.url)
            otherwise()

    def write_json(self, success, response={}):
        self.add_header('Content-Type', 'application/json')
        response.update({ 'success':success })
        self.response.write(json.dumps(response))

