import logging
import traceback
from argparse import ArgumentParser, Namespace
from pathlib import Path
from typing import Optional, List

from bagsy.convert.rosmsg import parse_bag
from bagsy.logger import setup_logging
from bagsy.parser import parse_and_exec
from bagsy.std import keep_only_alpha_numerical

logger = logging.getLogger(__name__)


# === command line interface

def setup_parser(parser: ArgumentParser) -> None:
    parser.add_argument("bag_path", type=Path, help="Path to rosbag")
    parser.add_argument("--output", "-o", type=Path, help="Output directory", default=None)
    parser.add_argument("--topic", "-t", type=str, help="The topics to extract", action='append')
    # TODO --no-covariance
    # TODO --rpy
    # TODO change frame (odom/pose/orientation)


def exec_cmd(args: Namespace, _: ArgumentParser):
    output_path = args.output
    # default save location is the current folder with the name of the page as the folder
    if output_path is None:
        output_path = Path("./") / keep_only_alpha_numerical(args.bag_path.stem)
    output_path.mkdir(exist_ok=True, parents=True)

    if args.topic is None:
        logger.info(f"Please specify at least one topic to extract.")
        return

    try:
        data = parse_bag(args.bag_path, args.topic, output_path)
        for (topic, df) in data.items():
            df.to_csv(output_path / (keep_only_alpha_numerical(topic) + ".csv"), index=False)
    except Exception:
        logger.error(f"Unexpected error while exporting data.")
        logger.warning(f"{traceback.format_exc()}")


def main(cli_args: Optional[List[str]] = None):
    setup_logging(logging.INFO)

    parse_and_exec("bagsy.convert",
                   "bag-convert",
                   "A python cli tool to help in the conversion of rosbags.",
                   cli_args)


if __name__ == "__main__":
    main()
