import logging
from pathlib import Path

import zmq

from flandre.config import C, ISDEV
from flandre.nodes.Node import Node
from flandre.utils.Msg import MoveAxisMsg, KillMsg, SetSeqMetaMsg, SeqIdMinMax, SetBaseMsg, PlaybackSeqListMsg, \
    SeqIdList, SetSidMsg, RfFrameMsg
from flandre.utils.RfSequence import RfSequence

logger = logging.getLogger(__name__)


class Loader(Node):
    topics = [MoveAxisMsg, SetSeqMetaMsg, SetBaseMsg, SetSidMsg]

    def loop(self):
        playback_socket = self.context.socket(zmq.PUSH)
        playback_socket.bind(f"tcp://*:{C.playback_port}")

        base: Path | None = None

        rff = None
        while True:
            msg = self.recv()
            if isinstance(msg, MoveAxisMsg) and rff is not None:
                logger.debug(f'Move axis: {msg}')
                if msg.axis == 'S':
                    pass
            elif isinstance(msg, SetSidMsg):
                self.send(RfFrameMsg(1, rff.frames[msg.value]))

            elif isinstance(msg, SetSeqMetaMsg):
                if base is None:
                    continue
                if msg.target == 'playback':
                    logger.info(f'load {msg.name}')
                    rff = RfSequence(base / msg.name)
                    self.send(SeqIdMinMax(*rff.seq_id_minmax))
                    self.send(SeqIdList([f.meta.sequence_id for f in rff.frames]))
                    self.send(SetSidMsg(0))
            elif isinstance(msg, SetBaseMsg):
                base = Path(msg.value)
                seq_list = [f.name for f in base.glob('*')]
                if not seq_list:
                    logger.warning(f'No sequences found in {base}')
                else:
                    C.data_folder = base
                    if not ISDEV:
                        C.write_config()
                self.send(PlaybackSeqListMsg(seq_list))
            elif isinstance(msg, KillMsg):
                if msg.name == '':
                    break
