#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Syntax:
#   carheating-runner.py
#
# Description:
#   Reads status files on /tmp and turn on/off carheating
#

import linknx
import time
import datetime
import os

linknx_temperature="temp"
linknx_left_socket="car_heater_left"
linknx_right_socket="car_heater_right"

# Time adjustments in minutes, function of temperature
def time_adjustment(temperature):
    return max(0,60-round(temperature*3))


def read_file(name):
    text_file = open("/tmp/{}.txt".format(name), "r")
    value = text_file.read()
    text_file.close()
    return value

def check_logic(ready_time_hms, active, linknx_socket, now, now_plus_adjustment):
    if active == 'on':
        current_value=linknx.read(linknx_socket) # off/on
        now_adjusted_hms=now_plus_adjustment.strftime("%H:%M:%S")
        now_hms=now.strftime("%H:%M:%S")
        #print("linknx_socket="+linknx_socket+" ready_time_hms="+ready_time_hms+" now_hms="+now_hms+" now_adjusted_hms="+now_adjusted_hms)
        if now_hms > ready_time_hms and current_value == 'on': # turn me off
            #print("turn off "+linknx_socket)
            linknx.write(linknx_socket,'off')
        elif now_adjusted_hms > ready_time_hms and current_value == 'off' and now_hms < ready_time_hms: # turn me on
            #print("turn on "+linknx_socket)
            linknx.write(linknx_socket,'on')

while True:
    time.sleep(60)
    #print("Waking up...")

    if os.path.isfile("/tmp/left_time.txt"):
        left_time=read_file("left_time")
        left_active=read_file("left_active")
        right_time=read_file("right_time")
        right_active=read_file("right_active")

        temperature=float(linknx.read(linknx_temperature))
        adjustment_minutes=time_adjustment(temperature)
        now = datetime.datetime.now()
        now_plus_adjustment = now + datetime.timedelta(minutes = adjustment_minutes)
        #print("temperature="+str(temperature)+" adjustment="+str(adjustment_minutes))
        current_hour = int(now.strftime("%H"))
        # We do not want to trigger on different sides of midnight
        if current_hour < 22:
            check_logic(left_time, left_active, linknx_left_socket, now, now_plus_adjustment)
            check_logic(right_time, right_active, linknx_right_socket, now, now_plus_adjustment) 
