"""
Diff the tpgPatternSetup directories for relivant metadata of changes in patterns
"""

import os
import sys
import ScPatternSelect
import argparse

parser = argparse.ArgumentParser(
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description="pattern server for TPG:{SYS}:{UNIT}:PATTERNS and TPG:{SYS}:{UNIT}:MODE_FREQ_MAX",
)
parser.add_argument(
    "--SYS",
    default="SYS0",
    help="macro like argument for the pattern server, eg SYS0, B015...",
)
parser.add_argument(
    "--UNIT",
    default="1",
    help="macro like argument for the pattern server, eg 1,2,3...",
)
parser.add_argument(
    "--IOC",
    default="sioc-sys0-ts01",
    help="macro like argument for the pattern server, eg sioc-sys0-ts01, sioc-b015-ts01",
)
parser.add_argument(
    "--show-standard-burst",
    action="store_true",
    help="remove this action latter, tells it weather to ignore the long list of burst patterns that are being renamed",
)
parser.add_argument(
    "--string-print",
    action="store_true",
    help="prints patterns as one long stiring with no returns for commands and such",
)

args = parser.parse_args()

patt_globals = ScPatternSelect.tools.globals(args.SYS, args.UNIT, args.IOC)

# tps = TpgPatternSetup
def tpsReleaseTop():
    """
    Returns the path with all of the different releases of TpgPatternSetup
    returns none if path does not exist
    """
    temp_path = os.path.join(os.environ["IOC_DATA"], args.IOC, "patterns")
    if os.path.exists(temp_path):
        return temp_path
    return None


def tpsVersionTop(version: int):
    """
    Returns the path to the version of TpgPatternSetup
    Returns none if path does not exist
    """
    temp_path = os.path.join(tpsReleaseTop(), f"TpgPatternSetup-R{version}")
    if os.path.exists(temp_path):
        return temp_path
    return None


def tpsVersionVerifiedPath(version: int):
    """
    Returns the path to the verified files in the given version of TpgPatternSetup
    Returns None if path does not exist
    """
    temp_path = os.path.join(
        tpsReleaseTop(), f"TpgPatternSetup-R{version}", "patterns", "verified"
    )
    if os.path.exists(temp_path):
        return temp_path
    return None


def tpsVersionTestPath(version: int):
    """
    Returns the path to the verified files in the given version of TpgPatternSetup
    Returns None if path does not exist
    """
    temp_path = os.path.join(
        tpsReleaseTop(), f"TpgPatternSetup-R{version}", "patterns", "test"
    )
    if os.path.exists(temp_path):
        return temp_path
    return None

def tpsDiffPrint(action:str, patterns:list):
    """
    prints the action taken and the list of patterns nicely to be used by commands
    """
    if args.string_print:
        patts_str = " ".join(patterns)
        print(f"PATTERNS {action}: {patts_str}")
        return
    
    for pattern in patterns:
        print(f"{action}: {pattern}")



def tpsDiff(old_version: int, new_version: int):
    """ """
    print(tpsVersionVerifiedPath(old_version))
    print(tpsVersionVerifiedPath(new_version))
    old_comm = os.listdir(tpsVersionVerifiedPath(old_version))
    old_test = os.listdir(tpsVersionTestPath(old_version))

    new_comm = os.listdir(tpsVersionVerifiedPath(new_version))
    new_test = os.listdir(tpsVersionTestPath(new_version))

    # commissioned
    # in old_test and in new_comm, not in the other two

    # decommissioned
    # in old_comm and in new_test, not in the other two

    # added
    # not in old in new
    patts_added = tpsDiffAdded(old_comm, old_test, new_comm, new_test)
    tpsDiffPrint("Added", patts_added)

    # removed
    # in old not in new
    patts_removed = tpsDiffRemoved(old_comm, old_test, new_comm, new_test)
    tpsDiffPrint("Removed", patts_removed)

    # updated
    # check tpggui version

    # regenerated
    # check that generation dates match

def tpsDiffCommissioned(old_test, new_comm):
    """
    finds all newly commissioned patterns
    inputs
    -------
    old_comm
    old_test
    new_comm
    new_test
    """
    for patt_name in old_test:
        if patt_name in new_comm:
            print(f"COMMISSIONED: {patt_name}")

def tpsDiffDecommissioned(old_comm, new_test):
    """
    finds all decommissioned patterns
    """
    for patt_name in old_comm:
        if patt_name in new_test:
            print(f"DECOMMISSIONED: {patt_name}")

def tpsDiffAdded(old_comm, old_test, new_comm, new_test):
    """
    finds all added patterns
    """
    old = old_comm + old_test
    new = new_comm + new_test
    added_patts = []

    for patt_name in new:
        if patt_name not in old:
            if patt_name.__contains__("b_") and not args.show_standard_burst:
                continue
            added_patts.append(patt_name)

    return added_patts

def tpsDiffRemoved(old_comm, old_test, new_comm, new_test):
    """
    finds all removed patterns
    """
    old = old_comm + old_test
    new = new_comm + new_test
    removed_patts = []

    for patt_name in old:
        if patt_name not in new:
            if patt_name.__contains__(" ") and not args.show_standard_burst:
                continue
            removed_patts.append(patt_name)
    return removed_patts

def tpsDiffTpgGuiVer(old_comm, old_test, new_comm, new_test):
    """
    lists out patterns that changed tpggui versions
    """


def tpsDiffRegen(old_comm, old_test, new_comm, new_test):
    """
    lists out patterns that were regenerated
    """

def pattTpgGuiVer(pattern, tps_ver):
    """
    returns the tpggui version for the pattern for the tps version
    """

def pattGenTime(pattern, tps_ver):
    """
    returns the tpggui version for the pattern for the tps version
    """


if __name__ == "__main__":
    """ """
    #TODO: make this automatically diff the two latest versions and 
    tpsDiff("Prod",30)