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
from tools.metaParser import meta_parse
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"

"""
if args.SYS==None or args.UNIT==None or args.IOC==None:
    print("ERROR: --SYS, --UNIT, AND --IOC must be provided")
    sys.exit(1)
"""

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", "d"),
        ("LAST_RUN", "s"),
        ("IS_VERIFIED", "s"),
        (PATTERN_TYPE, "s"),
        (f"LASER{RATE_SFX}", "d"),
        (f"LASER{TSOURCE_SFX}", "s"),
        (f"LASER{BUNCHES_PER_TRAIN_SFX}", "d"),
        (f"LASER{BUNCH_SPACING_SFX}", "d"),
        (f"LASER{OFFSET_SFX}", "s"),
        (f"SC_DIAG0{RATE_SFX}", "d"),
        (f"SC_DIAG0{TSOURCE_SFX}", "s"),
        (f"SC_DIAG0{BUNCHES_PER_TRAIN_SFX}", "d"),
        (f"SC_DIAG0{BUNCH_SPACING_SFX}", "d"),
        (f"SC_DIAG0{OFFSET_SFX}", "s"),
        (f"SC_BSYD{RATE_SFX}", "d"),
        (f"SC_BSYD{TSOURCE_SFX}", "s"),
        (f"SC_BSYD{BUNCHES_PER_TRAIN_SFX}", "d"),
        (f"SC_BSYD{BUNCH_SPACING_SFX}", "d"),
        (f"SC_BSYD{OFFSET_SFX}", "s"),
        (f"SC_HXR{RATE_SFX}", "d"),
        (f"SC_HXR{TSOURCE_SFX}", "s"),
        (f"SC_HXR{BUNCHES_PER_TRAIN_SFX}", "d"),
        (f"SC_HXR{BUNCH_SPACING_SFX}", "d"),
        (f"SC_HXR{OFFSET_SFX}", "s"),
        (f"SC_SXR{RATE_SFX}", "d"),
        (f"SC_SXR{TSOURCE_SFX}", "s"),
        (f"SC_SXR{BUNCHES_PER_TRAIN_SFX}", "d"),
        (f"SC_SXR{BUNCH_SPACING_SFX}", "d"),
        (f"SC_SXR{OFFSET_SFX}", "s"),
        (f"SC_DASEL{RATE_SFX}", "d"),
        (f"SC_DASEL{TSOURCE_SFX}", "s"),
        (f"SC_DASEL{BUNCHES_PER_TRAIN_SFX}", "d"),
        (f"SC_DASEL{BUNCH_SPACING_SFX}", "d"),
        (f"SC_DASEL{OFFSET_SFX}", "s"),
        ("TAGS", "s"),
    ]
)

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

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):

        meta_path = patt_globals.get_meta_data_path(pattern_name, is_verified)
        print(meta_path)

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

        # retrieve data from meta.json if it exists
        if os.path.exists(meta_path):
            with open(meta_path, "r") as meta_json:
                meta_data = json.load(meta_json)
                print(meta_data)
            pattern_dict = 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 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
    )

    for row in patt_table_rows:
        print(row)
        print("\n")

    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:
            patterns = operation.value()
            
            for patt_idx, pattern in enumerate(patterns):
                self.commissionDecomissionPatt(pattern)

            pv.post(
                patterns, timestamp=time.time()
            )  # 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"])

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")
    # 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()
