import logging
import time
from abc import abstractmethod

import zmq

from flandre.BusClient import BusClient
from flandre.utils.Msg import Msg, KillMsg, TickMsg, Msg1


class Node:
    fp = BusClient.fp
    bp = BusClient.bp
    topics = []

    def __init__(self, enable_init=True, level=logging.INFO, conflare=False, broker=False):
        self.enable_init = enable_init
        self.isalive = True
        self.level = level
        self.conflare = conflare
        self.broker = broker

    def recv(self):
        return self.c.recv()

    def send(self, msg: Msg):
        return self.c.send(msg)

    @abstractmethod
    def loop(self):
        pass

    def setup(self):
        self.base_setup()
        self.custom_setup()

    def custom_setup(self):
        pass

    def base_setup(self):
        FORMAT = '[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s'
        FORMAT = '"%(pathname)s:%(lineno)d" [%(asctime)s.%(msecs)03d] %(levelname)s - %(message)s'
        logging.basicConfig(level=self.level, format=FORMAT, datefmt='%Y-%m-%d %H:%M:%S', )
        rootLogger = logging.getLogger()

        logFormatter = logging.Formatter(FORMAT, datefmt='%Y-%m-%d %H:%M:%S', )

        fileHandler = logging.FileHandler("log.log")
        fileHandler.setFormatter(logFormatter)
        rootLogger.addHandler(fileHandler)

        # consoleHandler = logging.StreamHandler()
        # consoleHandler.setFormatter(logFormatter)
        # rootLogger.addHandler(consoleHandler)

        self.context = zmq.Context()
        if self.enable_init:
            self.c = BusClient(*([KillMsg, Msg1] + self.topics), poller=True, conflare=self.conflare)

    def __call__(self, *args, **kwargs):
        self.setup()
        if not self.broker:
            time.sleep(0.2)
            self.send(TickMsg())
            self.recv()
        self.loop()
        print(self.__class__.__name__, 'exiting')
