from aiohttp import web
import docker
import aiodocker
import base64
import auth

client = docker.from_env()
docker = aiodocker.Docker()

async def start(request):
    if(not auth.authorise(request)):
        print("Not authorised")
        return web.Response(status=401)
    try:
        container = await getContainer(request) 
        await container.start()
        status=200
    except:
        status = 500
    return web.Response(status=status)

async def stop(request):
    if(not auth.authorise(request)):
        print("Not authorised")
        return web.Response(status=401)
    try:
        container = await getContainer(request) 
        await container.stop()
        status=200
    except:
        status=500
    return web.Response(status=status)

async def status(request):
    # if(not auth.authorise(request)):
    #     print("Not authorised")
    #     return web.Response(status=401)
    try: 
        running="error"
        running = getContainer(request).status
        s=200
    except:
        s=500
        running = ""
    finally:
        return web.Response(status=s, body=running)

async def command(request):
    if(not auth.authorise(request)):
        print("Not authorised")
        return web.Response(status=401)
    server = request.match_info['server']
    try:
        container = client.containers.get(server)
        b64cmd = request.match_info['command']
        print(b64cmd)
        cmd = base64.urlsafe_b64decode(b64cmd).decode('utf_8')
        print(cmd)        
        container.exec_run(cmd="/usr/local/bin/cmd " + str(cmd))
        s= 200
        running="Success"
    except:
        s=500
        print("Failed Command")
    finally:
        
        return web.Response(status=s)

async def logs(request):
    if(not auth.authorise(request)):
        print("Not authorised")
        return web.Response(status=401)
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    server = request.match_info['server']
    docker = aiodocker.Docker()
    container = await docker.containers.get(server)
    async for line in container.log(stdout=True, follow=True, tail=5000):
        if ws.closed:
            break
        #print(line) 
        await ws.send_str(line)
    await docker.close()
    print("Closed")
    return ws    

async def getContainer(request):
    server = request.match_info['server']
    return await docker.containers.get(server)