import datetime
import configuration

from bravaweb.utils import ResponseCode

from bravaweb.utils.log import *


async def View(environment, data, **args):

    Debug(f"View: Start Response Type {environment.response_type.__name__}")

    if not "token" in args and environment.auth_token:
        args["token"] = environment.auth_token

    response = environment.response_type()

    content = response.Response(data=data, route=environment.route, action=environment.action, **args)

    _headers = [
        response.header,
        (b"Content-Length", str(len(content)).encode(configuration.api.encoding)),
        (b"Accept-Ranges", b"bytes"),
        (b"X-Frame-Options", b"Deny")
    ]

    if environment.origin:
        _headers.append((b"Access-Control-Allow-Origin", environment.origin.encode(configuration.api.encoding)))

    await environment.send({
        'type': 'http.response.start',
        'status': ResponseCode.OK.code,
        'headers': _headers
    })

    await environment.send({
        'type': 'http.response.body',
        'body': content
    })
    
    Debug(f"View: Finalized Response")
