import machine
import time
import gc

from microdot import Microdot, send_file, Request, Response

from microdot.utemplate import Template

led = machine.Pin(15, machine.Pin.OUT)

app = Microdot()
Response.default_content_type = 'text/html'
Request.max_content_length = 1024 * 1024


def cmd_parse(method, args):
    if method == 'GET':
        if 'cmd' in args:
            cmd = args['cmd']

            if 'reboot' == cmd:
                for x in range(2):
                    led.on()
                    time.sleep_ms(200)
                    led.off()
                    time.sleep_ms(200)

                machine.reset()

            if 'ftp' == cmd:
                exec(open('ftp.py').read())


@app.route('/static/<path:path>')
async def static(request, path):
    if '..' in path:
        # directory traversal is not allowed
        return 'Not found', 404
    return send_file('static/' + path)


@app.get('/file')
async def file(request):
    return send_file('templates/upload.html')


@app.post('/upload')
async def upload(request):
    filename = request.headers['Content-Disposition'].split('filename=')[1].strip('"')
    size = int(request.headers['Content-Length'])

    filename = filename.replace('/', '_')

    with open('/' + filename, 'wb') as f:
        while size > 0:
            chunk = await request.stream.read(min(size, 1024))
            f.write(chunk)
            size -= len(chunk)

    print('Successfully saved file: ' + filename)
    return ''


@app.route('/')
async def index(request):
    # print(request.args, request.path, request.method, sep='\n')
    # print(request.url, request.query_string, request.url_args, sep='\n')
    print(request.args)

    cmd_parse(request.method, request.args)

    ram_f = gc.mem_free()
    ram_a = gc.mem_alloc()
    ram_t = ram_a + ram_f
    return Template('index.html').render(ram_free=int(ram_f / 1024), ram_total=int(ram_t / 1024))


print('HTTP server started')
app.run(port=80)
