"""Max Water System driver code."""
import threading
import sys
import logging
import time
from random import randint
from Channel import write_tag, read_tag
from device_base import deviceBase
from utilities import get_public_ip_address
import json

# LOGGING SETUP
from logging.handlers import RotatingFileHandler

log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')
logFile = './advvfdipp.log'
my_handler = RotatingFileHandler(logFile, mode='a', maxBytes=500*1024, backupCount=2, encoding=None, delay=0)
my_handler.setFormatter(log_formatter)
my_handler.setLevel(logging.INFO)
logger = logging.getLogger('advvfdipp')
logger.setLevel(logging.INFO)
logger.addHandler(my_handler)

console_out = logging.StreamHandler(sys.stdout)
console_out.setFormatter(log_formatter)
logger.addHandler(console_out)

logger.info("advvfdipp startup")

PLC_IP_ADDRESS = "192.168.1.10"
WATCHDOG_SEND_PERIOD = 3600  # seconds


class start(threading.Thread, deviceBase):
    """Driver class."""

    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 = "8"
        self.finished = threading.Event()
        threading.Thread.start(self)

    def register(self):
        """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."""
        self.channels["status"]["last_value"] = ""

    def run(self):
        """Run the driver."""
        wait_sec = 30
        for i in range(0, wait_sec):
            print("advvfdipp driver will start in {} seconds".format(wait_sec - i))
            time.sleep(1)
        logger.info("BOOM! Starting advvfdipp driver...")

        self.nodes["advvfdipp_0199"] = self

        public_ip_address = get_public_ip_address()
        self.sendtodbDev(1, 'public_ip_address', public_ip_address, 0, 'advvfdipp')
        watchdog = self.advvfdipp_watchdog()
        self.sendtodbDev(1, 'watchdog', watchdog, 0, 'advvfdipp')
        watchdog_send_timestamp = time.time()

        watchdog_loops = 0
        watchdog_check_after = 5000

        while True:
            self.nodes["advvfdipp_0199"] = self
            watchdog_loops += 1
            if (watchdog_loops >= watchdog_check_after):
                test_watchdog = self.advvfdipp_watchdog()
                if not test_watchdog == watchdog or (time.time() - watchdog_send_timestamp) > WATCHDOG_SEND_PERIOD:
                    self.sendtodbDev(1, 'watchdog', test_watchdog, 0, 'advvfdipp')
                    watchdog = test_watchdog

                test_public_ip = get_public_ip_address()
                if not test_public_ip == public_ip_address:
                    self.sendtodbDev(1, 'public_ip_address', test_public_ip, 0, 'advvfdipp')
                    public_ip_address = test_public_ip
                watchdog_loops = 0
            time.sleep(15)

    def advvfdipp_watchdog(self):
        """Write a random integer to the PLC and then 1 seconds later check that it has been decremented by 1."""
        randval = randint(0, 32767)
        write_tag(str(PLC_IP_ADDRESS), 'watchdog_INT', randval)
        time.sleep(1)
        watchdog_val = read_tag(str(PLC_IP_ADDRESS), 'watchdog_INT')
        try:
            return (randval - 1) == watchdog_val[0]
        except (KeyError, TypeError):
            return False

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

    def advvfdipp_writeplctag(self, name, value):
        """Write a value to the PLC."""
        try:
            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)
            logger.warning("Result of advvfdipp_writeplctag(self, {}, {}) = {}".format(name, value, w))
            if w is None:
                w = "Error writing to PLC..."
            return w
        except Exception as e:
            logger.warning("GOT EXCEPTION in advvfdipp_writeplctag(self, {}, {}) => {}".format(name, value, e))
            return e
