#!/usr/bin/env python
# -*- coding:utf-8 -*-

__author__ = 'ghost'

import urlparse
import tornado.web
from tornado.httputil import HTTPServerRequest
from .auth.models import User


class BaseAuthHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        cookie = self.get_secure_cookie('user')
        if cookie:
            self._current_user = User.getone(pk=int(cookie))
            return self._current_user
        self.clear_cookie('user')
        return


def extract_params(request):
    if not isinstance(request, HTTPServerRequest):
        request = request.request

    parse_url = urlparse.urlparse(request.uri)
    path, params, query, fragment = parse_url.path, parse_url.params, parse_url.query, parse_url.fragment
    uri = urlparse.urlunparse((request.protocol, request.host, path, params, query, fragment))

    http_method = request.method
    headers = request.headers
    if 'wsgi.input' in headers:
        del headers['wsgi.input']
    if 'wsgi.errors' in headers:
        del headers['wsgi.errors']
    if 'HTTP_AUTHORIZATION' in headers:
        headers['Authorization'] = headers['HTTP_AUTHORIZATION']

    body = request.body

    return uri, http_method, body, headers