import logging
import time
from datetime import datetime, timedelta
from pathlib import Path
from typing import Iterator

import h5py

from . import protocols

logger = logging.getLogger(__name__)


class FileCSIPRoducer:
    is_live = False

    def __init__(self, path: Path) -> None:
        self.path = path
        if not self.path.exists():
            raise FileNotFoundError(f"File {self.path} does not exist")

    def __call__(self) -> Iterator[protocols.MergedCSI]:
        """
        Replay the CSI data from the file.
        """
        logger.info(f"Replaying CSI data from {self.path}")
        with h5py.File(self.path, "r") as file:
            try:
                for key in file:
                    datetime.fromisoformat(key)
            except ValueError as e:
                logger.exception(
                    "The file provided was not generated using this software", e
                )

            start_time = datetime.fromisoformat(list(file.keys())[0])
            target_offset = datetime.now() - start_time
            for key in file:
                logger.debug(f"Sending data from {key} at {datetime.now().isoformat()}")

                # TODO: add raw frames
                yield protocols.MergedCSI(
                    frames={},
                    matrix=file[key][:],
                )

                curr_time_virtual = datetime.fromisoformat(key)
                new_offset = datetime.now() - curr_time_virtual
                logger.debug(f"New offset {new_offset}, target is {target_offset}")
                if new_offset > target_offset + timedelta(seconds=1):
                    logger.warning(
                        f"Data is {new_offset - target_offset} behind, lagging behind..."
                    )
                time.sleep(max(0, (target_offset - new_offset).total_seconds()))

    def stop(self) -> None:
        """
        Stop the producer.
        """
        logger.info("Stopping file CSI producer")
