import os
import sys
from p4p.nt import NTTable
from p4p.server import Server as PVAServer
from p4p.server.thread import SharedPV
from p4p.client.thread import Context
from time import sleep
from epics import caput
from app.config_logging import config_logging
import time
from tools.patternNameParser import parse_pattern_name
import tools.patternParsers
import tools.globals as tg
import json
from threading import Thread
import argparse
import ScPatternSelect
import shutil


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",
)
# args = parser.parse_intermixed_args()
args = parser.parse_args()

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

RATE_SFX = patt_globals.RATE_SFX
TSOURCE_SFX = patt_globals.TSOURCE_SFX
BUNCHES_PER_TRAIN_SFX = patt_globals.BUNCHES_PER_TRAIN_SFX
BUNCH_SPACING_SFX = patt_globals.BUNCH_SPACING_SFX
OFFSET_SFX = patt_globals.OFFSET_SFX
PATTERN_TYPE = patt_globals.PATTERN_TYPE

MODE_FREQ_MAX_DEFS = "modeFreqMaxDef.json"

patt_table_name = patt_globals.get_patt_table_name()
mode_table_name = patt_globals.get_mode_table_name()
tag_table_name = patt_globals.get_tag_table_name()
verified_patt_path = patt_globals.get_verified_patt_path()
test_patt_path = patt_globals.get_test_patt_path()
heartbeat_pv = patt_globals.get_patt_table_heartbeat_pv()
tag_path = os.path.join(patt_globals.get_tag_path(), "pattern_tags.json")

print(patt_table_name)
print(mode_table_name)
print(verified_patt_path)
print(test_patt_path)
print(heartbeat_pv)

try:
    logger = config_logging()
except:
    print("unable to log")

# Define the structure of the patterns table (what are the columns called, and what data type each column has)
patt_table_type = NTTable(
    [
        ("PATTERN_NAME", "s"),  # ("PATTERN_TYPE", "s"), ("MULTI_DEST_MODE", "s"),
        ("RUN_COUNT", "i"),
        ("LAST_RUN", "d"),
        ("IS_VERIFIED", "s"),
        (PATTERN_TYPE, "s"),
        (f"LASER{RATE_SFX}", "i"),
        (f"LASER{TSOURCE_SFX}", "s"),
        (f"LASER{BUNCHES_PER_TRAIN_SFX}", "i"),
        (f"LASER{BUNCH_SPACING_SFX}", "i"),
        (f"LASER{OFFSET_SFX}", "s"),
        (f"SC_DIAG0{RATE_SFX}", "i"),
        (f"SC_DIAG0{TSOURCE_SFX}", "s"),
        (f"SC_DIAG0{BUNCHES_PER_TRAIN_SFX}", "i"),
        (f"SC_DIAG0{BUNCH_SPACING_SFX}", "i"),
        (f"SC_DIAG0{OFFSET_SFX}", "s"),
        (f"SC_BSYD{RATE_SFX}", "i"),
        (f"SC_BSYD{TSOURCE_SFX}", "s"),
        (f"SC_BSYD{BUNCHES_PER_TRAIN_SFX}", "i"),
        (f"SC_BSYD{BUNCH_SPACING_SFX}", "i"),
        (f"SC_BSYD{OFFSET_SFX}", "s"),
        (f"SC_HXR{RATE_SFX}", "i"),
        (f"SC_HXR{TSOURCE_SFX}", "s"),
        (f"SC_HXR{BUNCHES_PER_TRAIN_SFX}", "i"),
        (f"SC_HXR{BUNCH_SPACING_SFX}", "i"),
        (f"SC_HXR{OFFSET_SFX}", "s"),
        (f"SC_SXR{RATE_SFX}", "i"),
        (f"SC_SXR{TSOURCE_SFX}", "s"),
        (f"SC_SXR{BUNCHES_PER_TRAIN_SFX}", "i"),
        (f"SC_SXR{BUNCH_SPACING_SFX}", "i"),
        (f"SC_SXR{OFFSET_SFX}", "s"),
        (f"SC_DASEL{RATE_SFX}", "i"),
        (f"SC_DASEL{TSOURCE_SFX}", "s"),
        (f"SC_DASEL{BUNCHES_PER_TRAIN_SFX}", "i"),
        (f"SC_DASEL{BUNCH_SPACING_SFX}", "i"),
        (f"SC_DASEL{OFFSET_SFX}", "s"),
        ("IS_PINNED", "s"),
        ("TAGS", "s"),
    ]
)

mode_table_type = NTTable(
    [
        ("MODE", "s"),
        ("LASER", "i"),
        ("SC_DIAG0", "i"),
        ("SC_BSYD", "i"),
        ("SC_HXR", "i"),
        ("SC_SXR", "i"),
        ("SC_DASEL", "i"),
    ]
)

tag_table_type = NTTable([("TAG", "s"), ("TAG_ID", "i")])


def make_patt_list(patt_path):
    # look for patterns for patt_table
    pattern_names = []

    for possible_pattern in os.listdir(patt_path):
        possible_pattern_full_path = os.path.join(patt_path, possible_pattern)
        if os.path.isdir(possible_pattern_full_path):
            pattern_names.append(possible_pattern)

    return pattern_names


def append_to_patt_table_rows(
    patt_table_rows, directory_pattern_names, is_verified=False
):
    for index, pattern_name in enumerate(directory_pattern_names):

        init_pattern_dict = tools.patternParsers.pattern_dict_init(
            pattern_name, is_verified
        )
        
        meta_data = getMetaData(pattern_name, is_verified)

        # retrieve data from meta.json if it exists
        if meta_data is not None:
            pattern_dict = tools.patternParsers.meta_parse(meta_data, init_pattern_dict)

        elif pattern_name.__contains__(" "):
            pattern_dict = init_pattern_dict | parse_pattern_name(pattern_name)

        patt_table_rows.append(pattern_dict)

    return patt_table_rows
    
def getMetaData(pattern_name:str, is_verified:str)->dict:
    """
    Returns the meta data as a string
    Returns None if meta data does not exist
    
    inputs
    -------
    pattern_name:
        name of the pattern
    is_verified:
        verification status of the pattern
        
    outputs
    -------
    meta_data:
        dictionary of the meta.json file
    None:
        meta.json does not exist for this pattern
    """
    meta_path = patt_globals.get_meta_data_path(pattern_name, is_verified)
    if os.path.exists(meta_path):
        with open(meta_path, "r") as meta_json:
            meta_data = json.load(meta_json)
        return meta_data
        
    return None
    
def saveMetaData(pattern_name:str, is_verified:str, meta_data:dict):
    """
    Writes to the given pattern's meta.json file
    
    inputs
    --------
    pattern_name:
        name of the pattern
    is_verified:
        verification status of the pattern
    meta_data:
        dictionary of meta data to be written to meta.json
        
    output
    -------
    no output
    """
    meta_path = patt_globals.get_meta_data_path(pattern_name, is_verified)
    try:
        with open(meta_path, "w") as f:
            json.dump(meta_data, f, indent=4)
    except IOError as e:
        print(f"An error occurred while writing to file '{meta_data}': {e}")


def init_patt_table(patt_table_type):
    verified_patt_names = make_patt_list(verified_patt_path)
    test_patt_names = make_patt_list(test_patt_path)
    patt_table_rows = []
    patt_table_rows = append_to_patt_table_rows(
        patt_table_rows, verified_patt_names, is_verified=True
    )
    patt_table_rows = append_to_patt_table_rows(
        patt_table_rows, test_patt_names, is_verified=False
    )

    type_n = {}
    for patt_type in tg.PATTERN_TYPES:
        type_n[patt_type] = 0

    for patt in patt_table_rows:
        for patt_type in tg.PATTERN_TYPES:
            if patt[tg.PATTERN_TYPE] == patt_type:
                type_n[patt_type] = type_n[patt_type] + 1

    
    extra_row_n = 0
    extra_rows = patt_table_rows

    for i in range(extra_row_n):
        patt_table_rows = patt_table_rows + extra_rows
    print(f"added {extra_row_n}*{len(patt_table_rows)} extra rows to the nttable")
    print(type_n)
    print(f"initialized {len(patt_table_rows)} in the pattern table")

    initial_patt_table = patt_table_type.wrap(patt_table_rows, timestamp=time.time())
    return initial_patt_table


# now to the mode table initialization
def init_mode_table(mode_table_type):

    modeTablePath = os.path.join(os.getcwd(), "tools/", MODE_FREQ_MAX_DEFS)
    print(f"Sourcing mode table from: {modeTablePath}")
    if os.path.exists(modeTablePath):
        with open(modeTablePath) as modeTableData:
            mode_table_data = json.load(modeTableData)
            print("load complete")
    print(mode_table_data)
    initial_mode_table = mode_table_type.wrap(mode_table_data, timestamp=time.time())
    return initial_mode_table


def init_tag_table(tag_table_type):
    """ """

    print(f"Sourcing tag table from: {tag_path}")
    if os.path.exists(tag_path):
        with open(tag_path) as tag_file:
            tag_data = json.load(tag_file)
    else:
        tag_data = [{"TAG": "TEST", "TAG_ID": 0}]
        tag_json = json.dumps(tag_data, indent=4)
        try:
            with open(tag_path, "w") as tag_file:
                tag_file.write(tag_json)
        except:
            print(f"could not open file:{tag_path}")
    initial_tag_table = tag_table_type.wrap(tag_data, timestamp=time.time())
    return initial_tag_table


# Define a "handler" that gets called when somebody puts a value into a PV.
# In our case, this is sort of silly, because we just blindly dump whatever
# a client sends into the PV object.
# Do we want a put?
class Handler(object):
    def put(self, pv, operation):
        try:
            time_stamp=time.time()
            patterns = operation.value()
            
            for patt_idx, pattern in enumerate(patterns):
                self.commissionDecomissionPatt(pattern)
                self.savePattern(pattern, time_stamp)

            pv.post(
                patterns, timestamp=time_stamp
            )  # just store the value and update subscribers
            # spv.post(operation, timeStamp=time.time()) # just store the value and update subscribers
            # pv.post(operation.value())
            operation.done()

        except Exception as e:
            operation.done(error=str(e))

    def commissionDecomissionPatt(self, pattern):
        """
        checks that the pattern commission status matches the commission directory
        if it is the pattern commission status and directory do not match, moves the pattern
        """
        isInCommissionDir = self.isPatternInCommissionDir(pattern)
        #exit if 
        if isInCommissionDir is None:
            print(f"pattern does not exist: {pattern['PATTERN_NAME']}")
            return False
        
        #if pattern is commissioned in table but is in the test dir, move it to the comm dir
        if pattern["IS_VERIFIED"] == "True" and not self.isPatternInCommissionDir(pattern):
            destinaion = self.getFullCommPath(pattern)
            source = self.getFullTestPath(pattern)
            shutil.move(source, destinaion)
            return True
        
        #if pattern is not commissioned in table but is in the verified dir, move it to the test dir
        if pattern["IS_VERIFIED"] == "False" and self.isPatternInCommissionDir(pattern):
            source = self.getFullCommPath(pattern)
            destinaion = self.getFullTestPath(pattern)
            shutil.move(source, destinaion)
            return True
        
    def isPatternInCommissionDir(self, pattern):
        """
        checks that the pattern is in the commissioned patterns directory
        if it is in the test directory
        Output
        -------
        True:
            pattern is in the commissioned patterns directory
        False:
            pattern is in the test patterns directory
        None:
            pattern is in neither directory
        """
        
        full_comm_path = self.getFullCommPath(pattern)
        if os.path.exists(full_comm_path):
            return True
        
        full_test_path = self.getFullTestPath(pattern)
        if os.path.exists(full_test_path):
            return False
        
        return None
    
    def getFullCommPath(self, pattern):
        """
        Returns the path of the pattern if it were commissioned
        """
        return os.path.join(patt_globals.get_verified_patt_path(), pattern["PATTERN_NAME"])

    def getFullTestPath(self, pattern):
        """
        Returns the full path of the pattern if it is in the test dir
        """
        return os.path.join(patt_globals.get_test_patt_path(), pattern["PATTERN_NAME"])
    
    def savePattern(self, pattern, timestamp):
        """
        """
        # TODO: compare timestamp to last run of each pattern, then only open .json if they are within 60s
        # TODO: put all values that I want to save in this function
        if timestamp - 60 <= pattern["LAST_RUN"]:
            print(pattern["PATTERN_NAME"])
            #meta_data = getMetaData(pattern, pattern["IS_VERIFIED"])
            #meta_data["run_count"] = pattern["RUN_COUNT"]
            #meta_data["last_run"] = pattern["LAST_RUN"]
            #saveMetaData(pattern["PATTERN_NAME"], pattern["IS_VERIFIED"], meta_data)
            # 
            # open json, append last run and run count
            return
            
            
            
class TagHandler(object):
    def put(self, pv, operation):
        """
        try:
            with open(tag_path) as tag_file:
                tag_data = json.load(tag_file)
            pass
        except:
            pass

        tag_data
        """
        print(pv)
        print(type(pv))
        # print(pv['value'])

        try:
            pv.post(
                operation.value(), timestamp=time.time()
            )  # just store the value and update subscribers
            operation.done()

        except Exception as e:
            operation.done(error=str(e))


def server_heartbeat():
    """
    Infinite loop that increments a heartbeat PV
    Used for threading
    """
    print("starting heartbeat")
    counter = 0

    while True:
        counter = counter + 1
        try:
            caput(f"{heartbeat_pv}", counter)
        except:
            print(f"{heartbeat_pv} pv is down")
        sleep(3)


def patt_server():
    """
    Infinite loop that keeps up the PVAServer
    Used for threading
    """
    print("Starting Server")
    try:
        logger.info("Server Starting")
    except:
        print("unable to log")

    print("test test test")
    # The following line is an infinite loop
    PVAServer.forever(
        providers=[
            {patt_table_name: patt_pv, mode_table_name: mode_pv, tag_table_name: tag_pv}
        ]
    )


if __name__ == "__main__":
    # Define the PVs that will be hosted by the server.
    patt_pv = SharedPV(
        nt=patt_table_type, initial=init_patt_table(patt_table_type), handler=Handler()
    )
    mode_pv = SharedPV(
        nt=mode_table_type, initial=init_mode_table(mode_table_type), handler=Handler()
    )
    tag_pv = SharedPV(
        nt=tag_table_type, initial=init_tag_table(tag_table_type), handler=TagHandler()
    )
    # Make the PVA Server.  This is where we define the names for each of the PVs we defined above.
    # By using "PVAServer.forever", the server immediately starts running, and doesn't stop until you
    # kill it.

    # use threading so the program can have a heartbeat
    server_thread = Thread(target=patt_server)
    heartbeat_thread = Thread(target=server_heartbeat)

    server_thread.start()
    heartbeat_thread.start()
    server_thread.join()
