import json
import tornado.web
import sys
import logging

logger = logging.getLogger('boilerplate.' + __name__)

class BaseHandler(tornado.web.RequestHandler):
  """A class to collect common handler methods - all other handlers should
  subclass this one.
  """
  def set_default_headers(self):
    self.set_header('Content-type', 'text/html; charset=UTF-8')
    self.set_header('Server', 'TornadoServer/4.5.1; Ubuntu; Python')

  def logueado(self):
    if not self.get_secure_cookie('usuario'):
      print 'El usuario no se encuentra logueado'
      #self.redirect('http://softweb.pe')
    else:
      print 'Usuario logueado'

  def validar_permisos(self, permisos):
    if 1 in permisos:
      print 'si tiene los permisos'
      self.write("<h2>si tiene los permisos</h2>") 
    else:
      print 'no tiene los permisos'
      self.write("<h2>no tiene los permisos</h2>")
      self.finish() 

  def load_json(self):
    """Load JSON from the request body and store them in
    self.request.arguments, like Tornado does by default for POSTed form
    parameters.
    If JSON cannot be decoded, raises an HTTPError with status 400.
    """
    try:
      self.request.arguments = json.loads(self.request.body)
    except ValueError:
      msg = "Could not decode JSON: %s" % self.request.body
      logger.debug(msg)
      raise tornado.web.HTTPError(400, msg)

  def get_json_argument(self, name, default=None):
    """Find and return the argument with key 'name' from JSON request data.
    Similar to Tornado's get_argument() method.
    """
  if default is None:
    default = self._ARG_DEFAULT
  if not self.request.arguments:
    self.load_json()
  if name not in self.request.arguments:
    if default is self._ARG_DEFAULT:
      msg = "Missing argument '%s'" % name
      logger.debug(msg)
      raise tornado.web.HTTPError(400, msg)
    logger.debug("Returning default argument %s, as we couldn't find '%s' in %s" % (default, name, self.request.arguments))
    return default
  arg = self.request.arguments[name]
  logger.debug("Found '%s': %s in JSON arguments" % (name, arg))
  return arg
