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)
GUNRestartExtra_path = tools.globals.get_GUNRestartExtra_path(args.IOC)
heartbeat_pv = tools.globals.get_heartbeat_pv(args.SYS, args.UNIT)

print(patt_table_name)
print(mode_table_name)
print(GUNRestartExtra_path)
print(heartbeat_pv)

gunrestart_pattern_names = []
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"),
                        ("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")
                    ])

#look for patterns for patt_table
for possible_pattern in os.listdir(GUNRestartExtra_path):
    possible_pattern_full_path = os.path.join(GUNRestartExtra_path, possible_pattern)
    if os.path.isdir(possible_pattern_full_path):
        gunrestart_pattern_names.append(possible_pattern)
        #print(f'Adding \'{possible_pattern}\' to {patt_table_name}')

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


patt_table_rows = []
for index, pattern_name in enumerate(gunrestart_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(GUNRestartExtra_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"})

    
    patt_table_rows.append(pattern_dict)

initial_patt_table = patt_table_type.wrap(patt_table_rows, timestamp=time.time())
#print(patt_table_rows)

#now to the mode table initialization
mode_table_rows=[]

modeTablePath = os.path.join(os.getcwd(), 'tools/',tools.globals.MODE_FREQ_MAX_DEFS)
#print(modeTablePath)
if os.path.exists(modeTablePath):
    with open(modeTablePath) as modeTableData:
        mode_table_data = json.load(modeTableData)
        print("load complete")

initial_mode_table = mode_table_type.wrap(mode_table_data, timestamp=time.time())

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

# Define the PVs that will be hosted by the server.
patt_pv = SharedPV(nt=patt_table_type, initial=initial_patt_table, handler=Handler())
mode_pv = SharedPV(nt=mode_table_type, initial=initial_mode_table, handler=Handler())
# 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}])

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