import logging

from server.svc_pb2 import Packet
from server.model.db import Session
from server.model.models import Service

from server.model import create_service
from server.zeromq import sender


class MonitorHandler(object):
    def process_hello(self, pkt):
        svc_id = pkt.client_id

        session = Session()
        client = session.query(Service).filter_by(client_id=svc_id).first()
        if client is None:
            logging.info(f'{svc_id} not found, creating new one ...')

            hostname = pkt.hello.str_data[0]
            html_path = pkt.hello.str_data[1]
            event_port = int(pkt.hello.str_data[2])

            tmp = Packet()
            tmp.create.service.name = svc_id
            tmp.create.service.client_id = svc_id
            tmp.create.service.hostname = hostname
            tmp.create.service.html_path = html_path
            tmp.create.service.event_port = event_port
            tmp.create.service.active = False

            create_service(tmp.create.service)

        logging.info(f'Service connected, id: {svc_id}')

        rep = Packet()
        rep.client_id = svc_id
        rep.hello.to_id = svc_id
        sender.broadcast_services(rep.SerializeToString())

    def process_pong(self, pkt):
        svc_id = pkt.client_id
        logging.debug(f'PONG received: {svc_id}')


handler = MonitorHandler()


def process_svc_command(pkt):
    cmd_type = pkt.WhichOneof('oneof_data')
    if cmd_type == 'hello':
        handler.process_hello(pkt)
    elif cmd_type == 'pong':
        handler.process_pong(pkt)
    else:
        logging.error(f'Unhandled cmd: {cmd_type}')
