'''
This script checks the current 'canonical' colors and writes them
to a log file, along with info about the current time
The generated log file will be used to train our model.

For best results, this script should be scheduled to run frequently.
By default the install.py script will set it to run every 15 minutes -
if you want to change that, run `sudo crontab -e` and change the value
there.
'''

from colorsys import rgb_to_hsv
from datetime import datetime
from sys import exit
from argparse import ArgumentParser

import os

parser = ArgumentParser()
parser.add_argument(
    'webroot',
    type=str,
    help='Path to the directory where ambient light status is stored')
parser.add_argument(
    'savefile',
    type=str,
    help="Filename where logged data should be stored")

args = parser.parse_args()

FILE_DAT = args.savefile
WEB_ROOT = args.webroot
FILE_CANONICAL = os.path.join(WEB_ROOT, 'canonical')

print('Checking color from file {}'.format(FILE_CANONICAL))
print('Saving to file {}'.format(FILE_DAT))


DAT_HEADER = (
    '#\n# File generated by lightai_logger.py\n' +
    '# Each row represents the lighting status at the time of polling\n' +
    '# Format:\n' +
    '# day_of_year,day_of_week,second_of_day:rgb,hue,saturation,value\n' +
    '# , where rgb is a string representing an rgb color ' +
    'e.g. purple would be represented as \'255 0 255\'\n#\n\n'
)


def read_line(file, line_number=0):
    line = ""
    try:
        with open(file, 'r') as f:
            line = f.readlines()[line_number]
    except:
        pass
    return line


def string_to_rgb(string):
    r, g, b = [int(x) for x in string.split(" ")]
    return (r, g, b)

if __name__ == '__main__':
    now = datetime.now()
    day_of_year = now.timetuple().tm_yday
    day_of_week = now.timetuple().tm_wday

    midnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
    second_of_day = (now - midnight).seconds

    rgb_string = read_line(FILE_CANONICAL)
    if rgb_string is "":
        print('File could not be read properly: color is empty')
        exit(0)
    rgb_string = rgb_string.strip()
    r, g, b = string_to_rgb(rgb_string)
    hue, sat, val = rgb_to_hsv(r, g, b)

    file_already_exists = os.path.exists(FILE_DAT)

    with open(FILE_DAT, 'a') as f:
        if not file_already_exists:
            f.write(DAT_HEADER)

        f.write("{},{},{}:{},{},{},{}\n".format(
                day_of_year,
                day_of_week,
                second_of_day,
                rgb_string,
                hue,
                sat,
                val))
