from scripts.core.mqtt_handler import live_data
from threading import Thread
from scripts.core.GPIO_controller import turn_on
from scripts.util.logger import logger
from scripts.util.file_util import file_write
import time


class motorThread(Thread):
    def __init__(self):
        super().__init__()
        self.prev_time = int(time.time()) * 1000

    def run(self):
        while True:
            current_time = int(time.time()) * 1000
            # TODO: TIME BASED LOGIC TO SET prev_totalized_value = 0
            start = time.strptime(time.strftime(
                '%Y-%m-%d %H:%M:%S', time.localtime(self.prev_time / 1000)), '%Y-%m-%d %H:%M:%S')
            end = time.strptime(time.strftime('%Y-%m-%d %H:%M:%S',
                                              time.localtime(current_time / 1000)), '%Y-%m-%d %H:%M:%S')
            start_day = start.tm_mday
            end_day = end.tm_mday
            if start_day != end_day:
                logger.info('Turning on motor at {}'.format(str(time.time())))
                turn_on()
            else:
                pass
            self.prev_time = current_time
            time.sleep(1)


class mqttThread(Thread):
    def run(self):
        live_data()


if __name__ == '__main__':

    file_write(content={"status": "on"})
    motor = motorThread()
    motor.start()
    mqtt = mqttThread()
    mqtt.start()
