"""
A much smaller nttable for testing how nttables work
"""

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

# Define the structure of the patterns table (what are the columns called, and what data type each column has)
test_table_type = NTTable(
    [
        ("STRING", "s"),  # ("PATTERN_TYPE", "s"), ("MULTI_DEST_MODE", "s"),
        ("INTEGER", "d"),
    ]
)

test_table_name = "nttable:test:pv:timing"


def append_to_test_table_rows(
    test_table_rows
):
    for index in range(0,2):
        row = {"STRING":f"string{index}", "INTEGER": index}
        test_table_rows.append(row)

    

    return test_table_rows


def init_test_table(test_table_type):
    test_table_rows = []
    test_table_rows = append_to_test_table_rows(
        test_table_rows
    )

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

    initial_test_table = test_table_type.wrap(test_table_rows, timestamp=time.time())
    return initial_test_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:
            # get data from pv, this intercepts the put before the pv updates
            patterns = operation.value()
            
            for patt_idx, pattern in enumerate(patterns):
                for data in pattern:
                    if pattern[data] == 0:
                        patterns[patt_idx][data] = 5
                    if type(pattern[data]) == str:
                        patterns[patt_idx][data] = pattern[data].replace("\"","")
            
            #Send data to the pv
            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 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=[
            {test_table_name: test_pv}
        ]
    )


if __name__ == "__main__":
    # Define the PVs that will be hosted by the server.
    test_pv = SharedPV(
        nt=test_table_type, initial=init_test_table(test_table_type), 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.

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

    server_thread.start()
    server_thread.join()
