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.globals
import json
from threading import Thread
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")
#args = parser.parse_intermixed_args()
args = parser.parse_args()

"""
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 = tools.globals.get_patt_table_name(args.SYS, args.UNIT)
mode_table_name = tools.globals.get_mode_table_name(args.SYS, args.UNIT)
tag_table_name = tools.globals.get_tag_table_name(args.SYS, args.UNIT)
verified_patt_path = tools.globals.get_verified_patt_path(args.IOC)
test_patt_path = tools.globals.get_test_patt_path(args.IOC)
heartbeat_pv = tools.globals.get_heartbeat_pv(args.SYS, args.UNIT)
tag_path = os.path.join(tools.globals.get_tag_path(args.IOC), '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"),
                        ("LASER_RATE_Hz", "d"), ("LASER_TIMING_SOURCE", "s"), ("LASER_BUNCHES_PER_TRAIN", "d"), ("LASER_BUNCH_SPACING", "d"),
                        ("SC_DIAG0_RATE_Hz", "d"), ("SC_DIAG0_TIMING_SOURCE", "s"), ("SC_DIAG0_BUNCHES_PER_TRAIN", "d"), ("SC_DIAG0_BUNCH_SPACING", "d"),
                        ("SC_BSYD_RATE_Hz", "d"), ("SC_BSYD_TIMING_SOURCE", "s"), ("SC_BSYD_BUNCHES_PER_TRAIN", "d"), ("SC_BSYD_BUNCH_SPACING", "d"),
                        ("SC_HXR_RATE_Hz", "d"), ("SC_HXR_TIMING_SOURCE", "s"), ("SC_HXR_BUNCHES_PER_TRAIN", "d"), ("SC_HXR_BUNCH_SPACING", "d"),
                        ("SC_SXR_RATE_Hz", "d"), ("SC_SXR_TIMING_SOURCE", "s"), ("SC_SXR_BUNCHES_PER_TRAIN", "d"), ("SC_SXR_BUNCH_SPACING", "d"),
                        ("SC_DASEL_RATE_Hz", "d"), ("SC_DASEL_TIMING_SOURCE", "s"), ("SC_DASEL_BUNCHES_PER_TRAIN", "d"), ("SC_DASEL_BUNCH_SPACING", "d"),
                        ("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

# NOTE: p4p requires you to specify some initial value for every PV - there's not a default.
# here is where we make those default values.
# spin it up with all the meta data filled in.

def append_to_patt_table_rows(patt_table_rows, directory_pattern_names, is_verified=False):
    for index, pattern_name in enumerate(directory_pattern_names):
        pattern_dict = parse_pattern_name(pattern_name)
        pattern_dict.update({"PATTERN_NAME": pattern_name})
        # check to see if the partial meta data json exists
        # If not make it
        # If it does, read from it
        partial_meta_path = os.path.join(verified_patt_path,pattern_name,"partial_meta.json")
        partial_meta_default = {
                            "RUN_COUNT": 0,
                            "LAST_RUN": "None"
        }

        #retrieve data from partial_meta.json, will be replaced by meta.json
        if os.path.exists(partial_meta_path):
            with open(partial_meta_path, "r") as partial_meta_file:
                partial_meta_data=json.load(partial_meta_file)
            pattern_dict.update(partial_meta_data)

        #add default data to partial_meta.json if it does not exist
        else: 
            json_object = json.dumps(partial_meta_default,indent=4)
            try:
                with open(partial_meta_path, "w") as partial_meta_file:
                    partial_meta_file.write(json_object)
            except:
                print(f"could not open file:{partial_meta_path}")

            pattern_dict.update(partial_meta_default)

        pattern_dict.update({"TAGS":"TEST"})

        if is_verified:
            pattern_dict.update({"IS_VERIFIED":"True"})
        else:
            pattern_dict.update({"IS_VERIFIED":"False"})
        
        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)

    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/',tools.globals.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:
            pv.post(operation.value(), 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))

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

# 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.

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}])

#use threading so the program can have a heartbeat
server_thread = Thread(target= patt_server)
heartbeat_thread = Thread(target= server_heartbeat)
if __name__=="__main__":
    server_thread.start()
    heartbeat_thread.start()
    server_thread.join()