#! /usr/bin/python

# Convert unix time stamps to local time
# Usage: mikado-unix-time-to-local-time FILE
# Outputs to FILE.txt

from datetime import datetime
import glob
import re
import sys
import os
import rosparam

from pathlib import Path


def convert_date(match):
    return str(datetime.fromtimestamp(float(match.group(1))))


def convert_one(filename, out_filename):
    with open(filename, "r+") as file:
        with open(out_filename, "w") as out:
            data = (
                file.read().strip() + "\n"
            )  # skip empty lines at start in the oldest rosout.log[.*] file

            # multi-line follow-on data: quote in ``, move everything to 4th column
            data = re.sub(r"^(?!\d+\.\d+ )(.*)$", r";;; \1 ;", data, flags=re.MULTILINE)

            # place continuations of multiline output into the 4th column
            data = re.sub(
                r"^(\d+\.\d+)  (Node Startup)$",
                r"\1;;; `\2` ;",
                data,
                flags=re.MULTILINE,
            )  # handle first line

            data = re.sub(r" \[topics.*?\]", "", data)  # remove useless topic lists
            data = re.sub(
                r"^(\d+\.\d+) (\w+) (.+?) (\[.+?\]) (.*?)$",
                r"\1; \2; \3; `\5`; ",
                data,
                flags=re.MULTILINE,
            )  # replace the first 4 spaces with tabs
            data = re.sub(r"^(\d+\.\d+)", convert_date, data, flags=re.MULTILINE)
            out.write(data)

    print(
        "CSV output: '{}'  delimiter: semicolon ';'  strings quoted in: '`', input file was: {}".format(
            out_filename, filename
        )
    )
    return True


def help():
    print(
        (
            "Usage: {} [<options>] [FILE]\n\n"
            + "  (no args)        convert all rosout.log[.0-9] in the currently running Mikado, if it is running\n"
            + "  FILE             convert this single rosout logfile to CSV\n"
            + "  -h               display this usage guide\n"
            + "  -o OUT_DIR       write the CSV files to the folder OUT_DIR instead of to the location of the input file(s)\n"
            + "  -o OUT_DIR FILE  convert all rosout.log[.0-9] files in folder FILE and write to OUT_DIR instead of to the location of the input file(s)"
        ).format(os.path.basename(sys.argv[0]))
    )
    return False


def convert_latest(out_dir=None, in_dir=None):
    if in_dir:
        # check if in_dir is directory
        if os.path.isdir(in_dir):
            latest_dir = in_dir
        else:
            print("Error: expected directory as last argument\n")
            return help()
    else:
        # check if Mikado is running, look at ~/mikado/logs/project_name/latest/rosout.log
        try:
            cell_name = rosparam.get_param("/mikado/project_name")
            latest_dir = str(Path.home()) + "/mikado/logs/" + cell_name + "/latest/"
        except Exception as e:
            # if no cell running, error out
            print("Mikado currently not running.")
            return help()

    try:
        # convert all rosout.log*

        if not out_dir:
            out_dir = latest_dir

        latest_file = "rosout.log"
        f_out = os.path.join(out_dir, os.path.basename(latest_file)) + ".csv"

        convert_one(latest_dir + latest_file, f_out)
        outputs = [f_out]

        # handle rosout.log.1-9
        glob_path = latest_dir + latest_file + ".[0-9]"
        for f in glob.iglob(glob_path):
            f_out = os.path.join(out_dir, os.path.basename(f)) + ".csv"
            convert_one(f, f_out)
            outputs.append(f_out)

        print("Generated files:\n" + "\n".join(outputs))

        return outputs
    except Exception as e:
        print("Error: {}".format(str(e)))
        return False


def exit(success):
    if success:
        sys.exit(0)
    else:
        sys.exit(1)


if __name__ == "__main__":

    if len(sys.argv) == 2 and sys.argv[1] in ["--help", "-h"]:
        exit(help())

    if len(sys.argv) == 3 and sys.argv[1] in ["--out-dir", "-o"]:
        exit(convert_latest(out_dir=sys.argv[2]))

    if len(sys.argv) == 4 and sys.argv[1] in ["--out-dir", "-o"]:
        print("argv[3]: " + sys.argv[3])
        exit(convert_latest(out_dir=sys.argv[2], in_dir=sys.argv[3]))

    if len(sys.argv) == 1:
        exit(convert_latest())

    filename = sys.argv[1]
    out_filename = sys.argv[1] + ".csv"

    exit(convert_one(filename, out_filename))
