# coding:utf-8

import os

from makit.lib import ospath
from makit.web.context import Context


async def index(c: Context):
    app = c.app
    static_dir = os.path.join(app.config.SYSTEM.base_dir, 'static')
    html = os.path.join(static_dir, 'index.html')
    with open(html, 'r', encoding='utf-8') as h:
        content = h.read()
    return await c.respond_html(content)


async def static_file(c: Context):
    app = c.app
    path = c.scope['path']

    if path.startswith('/static'):
        path = path[7:]
    base_dir = app.base_dir
    filepath = ospath.join(base_dir, 'static', path)
    if not os.path.exists(filepath):
        filepath = ospath.join(base_dir, path)
        if not os.path.exists(filepath):
            return await c.respond_json('Not found', status_code=404)
    if path.endswith('.js'):
        with open(filepath, 'r', encoding='utf-8') as f:
            content = f.read()
        return await c.respond(content=content, headers={'content-type': 'text/javascript'})
    else:
        with open(filepath, 'rb') as f:
            content = f.read()
    if 'temp' in filepath:
        os.remove(filepath)
    return await c.respond(content=content)
