#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pickle
import asyncio
import logging
from JobManager import JobManager
from ClusterInfo import ClusterInfo

async def handle_read(reader, writer):
    data = await reader.read(1024)
    addr = writer.get_extra_info('peername')
    message = pickle.loads(data)
    command = message['cmd']
    job_name = message['job_name']

    if command == 'submit':
        job_file = message['job_file']
        jm.add_job(job_file, job_name)
        message = 'Job \'' + job_name + '\' submitted'
    elif command == 'prepare':
        jm.prepare_job(job_name)
        message = 'Preperation for job \'' + job_name + '\' done'
    elif command == 'run':
        jm.run_job(job_name)
        message = 'Job \'' + job_name + '\' running'
    elif command == 'pause':
        jm.pause_job(job_name)
        message = 'Job \'' + job_name + '\' pausing'
    elif command == 'cancel':
        jm.cancel_job(job_name)
        message = 'Job \'' + job_name + '\' canceled'

    writer.write(message.encode())
    await writer.drain()

logging.basicConfig(filename='JobManager.log', level=logging.DEBUG)
logger = logging.getLogger(__name__)

cluster_info = ClusterInfo()
jm = JobManager(cluster_info, logger)
jm_addr = cluster_info.job_manager_info.ip_addr
jm_port = cluster_info.job_manager_info.port

loop = asyncio.get_event_loop()
coro = asyncio.start_server(handle_read, jm_addr, jm_port, loop=loop)
server = loop.run_until_complete(coro)

try:
    loop.run_forever()
except KeyboardInterrupt:
    pass

server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
