import os
from p4p.nt import NTTable
from p4p.server import Server as PVAServer
from p4p.server.thread import SharedPV
from app.config_logging import config_logging
import time
from tools.patternNameParser import parse_pattern_name
import tools.globals
import json

patt_table_name = tools.globals.PATT_TABLE_NAME
mode_table_name = tools.globals.MODE_TABLE_NAME

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_PATTERN_TYPE", "s"), ("LASER_BUNCHES_PER_TRAIN", "d"), ("LASER_BUNCH_SPACING", "d"),
                        ("SC_DIAG0_RATE_Hz", "d"), ("SC_DIAG0_PATTERN_TYPE", "s"), ("SC_DIAG0_BUNCHES_PER_TRAIN", "d"), ("SC_DIAG0_BUNCH_SPACING", "d"),
                        ("SC_BSYD_RATE_Hz", "d"), ("SC_BSYD_PATTERN_TYPE", "s"), ("SC_BSYD_BUNCHES_PER_TRAIN", "d"), ("SC_BSYD_BUNCH_SPACING", "d"),
                        ("SC_HXR_RATE_Hz", "d"), ("SC_HXR_PATTERN_TYPE", "s"), ("SC_HXR_BUNCHES_PER_TRAIN", "d"), ("SC_HXR_BUNCH_SPACING", "d"),
                        ("SC_SXR_RATE_Hz", "d"), ("SC_SXR_PATTERN_TYPE", "s"), ("SC_SXR_BUNCHES_PER_TRAIN", "d"), ("SC_SXR_BUNCH_SPACING", "d"),
                        ("SC_DASEL_RATE_Hz", "d"), ("SC_DASEL_PATTERN_TYPE", "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(tools.globals.GUN_RESTART_EXTRA_PATH):
    possible_pattern_full_path = os.path.join(tools.globals.GUN_RESTART_EXTRA_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(tools.globals.GUN_RESTART_EXTRA_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.
print("Starting Server")
try:
    logger.info("Server Starting")
except:
    print('unable to log')
pva_server = PVAServer.forever(providers=[{patt_table_name: patt_pv, mode_table_name: mode_pv}])