"""Driver for connecting Pond Level to Meshify."""

import threading
from device_base import deviceBase
from Channel import Channel, write_tag, BoolArrayChannels
from Maps import transferstation_map as maps
import json
import time

_ = None

try:
    with open("persist.json", 'r') as persist_file:
        persist = json.load(persist_file)
except Exception:
    persist = {}

try:
    persist['last_schedule_history']
except KeyError:
    persist['last_schedule_history'] = {"id": -1}

_ = None

plc_ip_address = "192.168.1.10"


def reverse_map(value, map_):
    """Perform the opposite of mapping to an object."""
    for x in map_:
        if map_[x] == value:
            return x
    return None


bit_channels = [
    BoolArrayChannels(plc_ip_address, 'systemx_enabled', "cfg_SystemEnabled", "BOOL", _, 60*60*60, map_=maps['bit_channels']['system_enabled']),
    BoolArrayChannels(plc_ip_address, 'ltx1_enabled', "cfg_SystemLTEnabled", "BOOL", _, 60*60*60, map_=maps['bit_channels']['lt_enabled']),
    BoolArrayChannels(plc_ip_address, 'ftx1_enabled', "cfg_SystemFTEnabled", "BOOL", _, 60*60*60, map_=maps['bit_channels']['ft_enabled']),
    BoolArrayChannels(plc_ip_address, 'ptx2_enabled', "cfg_SystemBPDischargePTEnabled", "BOOL", _, 60*60*60, map_=maps['bit_channels']['ptx2_enabled']),
]

channels = [
    Channel(plc_ip_address, "lt01_level", "LTX1_PondLevel[0].Val", "REAL", 0.25, 3600),
    Channel(plc_ip_address, "lt11_level", "LTX1_PondLevel[1].Val", "REAL", 0.25, 3600),
    Channel(plc_ip_address, "lt21_level", "LTX1_PondLevel[2].Val", "REAL", 0.25, 3600),
    Channel(plc_ip_address, "lt31_level", "LTX1_PondLevel[3].Val", "REAL", 0.25, 3600),

    Channel(plc_ip_address, "pt11_pressure", "PTX1_BoosterPumpInlet[1].Val", "REAL", 3.0, 3600),
    Channel(plc_ip_address, "pt21_pressure", "PTX1_BoosterPumpInlet[2].Val", "REAL", 3.0, 3600),
    Channel(plc_ip_address, "pt31_pressure", "PTX1_BoosterPumpInlet[3].Val", "REAL", 3.0, 3600),

    Channel(plc_ip_address, "pt12_pressure", "PTX2_BoosterPumpDischarge[1].Val", "REAL", 3.0, 3600),
    Channel(plc_ip_address, "pt22_pressure", "PTX2_BoosterPumpDischarge[2].Val", "REAL", 3.0, 3600),
    Channel(plc_ip_address, "pt32_pressure", "PTX2_BoosterPumpDischarge[3].Val", "REAL", 3.0, 3600),

    Channel(plc_ip_address, "ft01_flow", "FTX1_SystemOutput[0].Val", "REAL", 5.0, 3600),
    Channel(plc_ip_address, "ft11_flow", "FTX1_SystemOutput[1].Val", "REAL", 5.0, 3600),
    Channel(plc_ip_address, "ft21_flow", "FTX1_SystemOutput[2].Val", "REAL", 5.0, 3600),
    Channel(plc_ip_address, "ft31_flow", "FTX1_SystemOutput[3].Val", "REAL", 5.0, 3600),

    # Channel(plc_ip_address, "run_status", "TransferStation.Running", "BOOL", _, 3600, map_=maps['run']),
    # Channel(plc_ip_address, "ft21_enabled", "cfg_SystemFTEnabled[2]", "BOOL", _, 3600),
    # Channel(plc_ip_address, "ft31_enabled", "cfg_SystemFTEnabled[3]", "BOOL", _, 3600),
]


class start(threading.Thread, deviceBase):
    """Start class required by Meshify."""

    def __init__(self, name=None, number=None, mac=None, Q=None, mcu=None, companyId=None, offset=None, mqtt=None, Nodes=None):
        """Initialize the driver."""
        threading.Thread.__init__(self)
        deviceBase.__init__(self, name=name, number=number, mac=mac, Q=Q, mcu=mcu, companyId=companyId, offset=offset, mqtt=mqtt, Nodes=Nodes)

        self.daemon = True
        self.version = "3"
        self.finished = threading.Event()
        self.forceSend = False
        threading.Thread.start(self)

    # this is a required function for all drivers, its goal is to upload some piece of data
    # about your device so it can be seen on the web
    def register(self):
        """Register the driver."""
        # self.sendtodb("log", "BOOM! Booted.", 0)
        pass

    def run(self):
        """Actually run the driver."""
        global persist
        wait_sec = 60
        for i in range(0, wait_sec):
            print("transferstation driver will start in {} seconds".format(wait_sec - i))
            time.sleep(1)
        print("BOOM! Starting transferstation driver...")
        # after its booted up assuming that M1 is now reading modbus data
        # we can replace the reference made to this device name to the M1 driver with this
        # driver. The 01 in the 0199 below is the device number you referenced in the modbus wizard
        self.nodes["transferstation_0199"] = self
        send_loops = 0
        while True:
            if self.forceSend:
                print "FORCE SEND: TRUE"

            # for c in channels:
            #     if c.read(self.forceSend):
            #         self.sendtodb(c.mesh_name, c.value, 0)
            #
            # for b in bit_channels:
            #     if b.read(self.forceSend):
            #         for v in b.last_value:
            #             self.sendtodb(v, b.last_value[v], 0)

            # print("transferstation driver still alive...")
            if self.forceSend:
                if send_loops > 2:
                    print("Turning off forceSend")
                    self.forceSend = False
                    send_loops = 0
                else:
                    send_loops += 1

    # def transferstation_sync(self, name, value):
    #     """Sync all data from the driver."""
    #     self.forceSend = True
    #     # self.sendtodb("log", "synced", 0)
    #     return True

    def transferstation_writeplctag(self, name, value):
        # """Write a value to the PLC."""
        new_val = json.loads(str(value).replace("'", '"'))
        tag_n = str(new_val['tag'])  # "cmd_Start"
        val_n = new_val['val']
        w = write_tag(str(plc_ip_address), tag_n, val_n)
        print("Result of transferstation_writeplctag(self, {}, {}) = {}".format(name, value, w))
        if w is None:
            w = "Error writing to PLC..."
        return w
