"""Driver for tankalarms"""

import threading
import json
import time
from random import randint
import os
from device_base import deviceBase
from Channel import PLCChannel, ModbusChannel,read_tag, write_tag, TAG_DATAERROR_SLEEPTIME
import persistence
from utilities import get_public_ip_address, get_private_ip_address
from file_logger import filelogger as log
PLC_IP_ADDRESS = "192.168.1.12"
from Tags import tags

_ = None

log.info("tankalarms startup")

# GLOBAL VARIABLES
WAIT_FOR_CONNECTION_SECONDS = 20
IP_CHECK_PERIOD = 60


CHANNELS = tags

# PERSISTENCE FILE
PERSIST = persistence.load()


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.force_send = False
        self.public_ip_address = ""
        self.public_ip_address_last_checked = 0
        self.private_ip_address = ""
        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."""
        for i in range(0, WAIT_FOR_CONNECTION_SECONDS):
            print("tankalarms driver will start in {} seconds".format(WAIT_FOR_CONNECTION_SECONDS - i))
            time.sleep(1)
        log.info("BOOM! Starting tankalarms driver...")

        self._check_ip_address()

        self.nodes["tankalarms_0199"] = self

        send_loops = 0

        while True:
            try:
                now = time.time()
                if self.force_send:
                    log.warning("FORCE SEND: TRUE")
                if int(time.time()) % 600 == 0 or self.force_send:
                    payload = {"ts": round(time.time()/600)*600*1000, "values": {}}
                    for chan in CHANNELS:
                        val = chan.read()
                        payload["values"][chan.mesh_name] = val

                    self._check_ip_address()
                    payload["values"]["public_ip_address"] = self.public_ip_address 
                    payload["values"]["private_ip_address"] = self.private_ip_address
                    self.sendToTB(json.dumps(payload))
                    time.sleep(TAG_DATAERROR_SLEEPTIME) # sleep to allow Micro800 to handle ENET requests    

                # print("tankalarms driver still alive...")
                if self.force_send:
                    if send_loops > 2:
                        log.warning("Turning off force_send")
                        self.force_send = False
                        send_loops = 0
                    else:
                        send_loops += 1

            
                
                
            except Exception as e:
                log.error(e)

   
    def _check_ip_address(self):
        """Check the public IP address and send to Meshify if changed."""
        self.public_ip_address_last_checked = time.time()
        test_public_ip = get_public_ip_address()
        test_public_ip = test_public_ip
        test_private_ip = get_private_ip_address()
        if not test_public_ip == self.public_ip_address and not test_public_ip == "0.0.0.0":
            #self.sendtodbDev(1, 'public_ip_address', test_public_ip, 0, 'tankalarms')
            self.public_ip_address = test_public_ip
        if not test_private_ip == self.private_ip_address:
            #self.sendtodbDev(1, 'private_ip_address', test_private_ip, 0, 'tankalarms')
            self.private_ip_address = test_private_ip
        hostname = "8.8.8.8"
        response = 1 
        try:
            response = os.system("ping -c 1 " + hostname + " > /dev/null 2>&1")
        except Exception as e:
            print("Something went wrong in ping: {}".format(e))

        #and then check the response...
        if response == 0:
            print(hostname, 'is up!')
            self.ping_counter = 0
        else:
            print(hostname, 'is down!')
            self.ping_counter += 1
    
        if self.ping_counter >= 3:
            print("Rebooting because no internet detected")
            os.system('reboot')
        
    
    def tankalarms_sync(self, name, value):
        """Sync all data from the driver."""
        self.force_send = True
        # self.sendtodb("log", "synced", 0)
        return True

    def tankalarms_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']
        write_res = write_tag(str(PLC_IP_ADDRESS), tag_n, val_n, plc_type="Micro800")
        print("Result of tankalarms_writeplctag(self, {}, {}) = {}".format(name, value, write_res))
        if write_res is None:
            write_res = "Error writing to PLC..."
        return write_res

    def tankalarms_alarmreset(self, name, value):
        log.info("Value received is {}".format(value))
        if value == 1 or value == "1":
            write_res = write_tag(str(PLC_IP_ADDRESS), "Reset", 1, plc_type="Micro800")
            log.info("Result of tankalarms_alarmreset {}, {}, {}".format(name, value, write_res))
            if write_res is None:
                write_res = "Error writing to PLC..."
            return write_res
        return False

    def tankalarms_water_hihi_spt(self, name, value):
        log.info("Value received is {}".format(value))
        write_res = write_tag(str(PLC_IP_ADDRESS), "WaterTx_HHSP", float(value), plc_type="Micro800")
        log.info("Result of tankalarms_water_hihi_spt {}, {}, {}".format(name, value, write_res))
        if write_res is None:
            write_res = "Error writing to PLC..."
        return write_res
        
    
    def tankalarms_water_hi_spt(self, name, value):
        log.info("Value received is {}".format(value))
        write_res = write_tag(str(PLC_IP_ADDRESS), "WaterTx_HSP", float(value), plc_type="Micro800")
        log.info("Result of tankalarms_water_hi_spt {}, {}, {}".format(name, value, write_res))
        if write_res is None:
            write_res = "Error writing to PLC..."
        return write_res

    def tankalarms_oil_hihi_spt(self, name, value):
        log.info("Value received is {}".format(value))
        write_res = write_tag(str(PLC_IP_ADDRESS), "OilTx_HHSP", float(value), plc_type="Micro800")
        log.info("Result of tankalarms_oil_hihi_spt {}, {}, {}".format(name, value, write_res))
        if write_res is None:
            write_res = "Error writing to PLC..."
        return write_res

    
    def tankalarms_oil_hi_spt(self, name, value):
        log.info("Value received is {}".format(value))
        write_res = write_tag(str(PLC_IP_ADDRESS), "OilTx_HSP", float(value), plc_type="Micro800")
        log.info("Result of tankalarms_oil_hi_spt {}, {}, {}".format(name, value, write_res))
        if write_res is None:
            write_res = "Error writing to PLC..."
        return write_res
   

