# -*- coding: utf-8 -*-


import tornado.options

from .engine import Engine as dpEngine

session_default_expire_in = tornado.options.options.session_exp_in or 7200


class Controller(dpEngine):
    def __init__(self, application, request, **kwargs):
        super(Controller, self).__init__()

        self.prefix = kwargs.get('prefix')
        self.parent = kwargs.get('parent')

        self._write = []
        self._finish = None
        self._render = None

        self.head_requested = False
        self.post_requested = False
        self.get_requested = False
        self.patch_requested = False
        self.delete_requested = False
        self.put_requested = False

    def initialize(self, prefix, parent=None):
        self.prefix = prefix
        self.parent = parent

    @property
    def request(self):
        return self.parent.request

    def get_argument(self, name, default=None, strip=True, cast=None, fmt=None):
        ret = self.parent.get_argument(name, default, strip)

        try:
            if ret and cast == int and fmt == 'yyyymmdd':
                try:

                    return self.helper.datetime.time(
                        self.helper.datetime.datetime(
                            yyyymmdd=self.helper.numeric.extract_numbers(ret or '')))

                except:
                    return False

            elif ret and cast == int:
                return int(ret)
            elif ret and cast == long:
                return long(ret)
            elif ret and cast == float:
                return float(ret)

        except ValueError:
            return default

        return ret

    def get_user_agent(self, parsed=True):
        return self.parent.get_user_agent(parsed=parsed)

    @property
    def remote_ip(self):
        return self.parent.remote_ip

    def set_secure_cookie(self, name, value, expires_days=30, version=2, **kwargs):
        return self.parent.set_secure_cookie(name, value, expires_days=expires_days, version=version, **kwargs)

    def get_secure_cookie(self, name, value=None, max_age_days=31, min_version=None):
        return self.parent.get_secure_cookie(name, value=value, max_age_days=max_age_days, min_version=min_version)

    def get_sessionid(self):
        return self.parent.get_sessionid()

    def set_sessionid(self, sessionid=None):
        return self.parent.set_sessionid(sessionid=sessionid)

    def get_session_value(self, name, expire_in=None, sessionid=None):
        return self.parent.get_session_value(name, expire_in=expire_in, sessionid=sessionid)

    def get_session_value_ttl(self, name):
        return self.parent.get_session_value_ttl(name)

    def set_session_value(self, name, value, expire_in=session_default_expire_in):
        return self.parent.set_session_value(name, value, expire_in=expire_in)

    def session(self, name, value=None, expire_in=session_default_expire_in):
        return self.parent.session(name, value=value, expire_in=expire_in)

    def _prefix(self, url):
        if 'X-Proxy-Prefix' in self.request.headers:
            prefix = self.request.headers['X-Proxy-Prefix']
            prefix = prefix[:-1] if prefix.endswith('/') else prefix

            if url.startswith(prefix):
                url = url[len(prefix):] or '/'

        return url

    def redirect(self, url, prefix=False, permanent=False, status=None):
        if hasattr(self.parent, '__postprocessed__'):
            return

        setattr(self.parent, '__postprocessed__', True)

        if prefix:
            url = self._prefix(url)

        try:
            self.parent.redirect(url, permanent, status)
        except (AttributeError, TypeError):
            pass

    def render(self, template_name, kwargs=None):
        self._render = {'t': template_name, 'k': kwargs}

    def render_string(self, template_name, kwargs=None):
        if kwargs:
            return self.view.render_string(self, template_name, kwargs)
        else:
            return self.view.render_string(self, template_name)

    def write(self, chunk):
        self._write.append(chunk)

    def finish(self, chunk=None):
        self._finish = chunk
