#!/usr/bin/env python3

import tkinter
import subprocess
import os
import pickle

     
class Logic:
    def __init__(self):
        try:
            with open(get_absolute_path('pickle_file'), 'rb') as pickle_file:
                self.data = pickle.load(pickle_file)
        except (FileNotFoundError, EOFError):
            self.data = Default()

    def handle_key(self, key):
        char = key.keysym
        if char in 'bk':
            self.increase_brightness()
        elif char in 'dj':
            self.decrease_brightness()
        elif char in 'wh':
            self.decrease_temperature()
        elif char in 'cl':
            self.increase_temperature()
        elif char in 'i':
            self.invert_colors()
            return
        elif char in 'r':
            subprocess.run(['redshift', '-x'])
            return
        elif char in '1of':
            self.data.brightness = 100
        elif char == 'Escape':
            self.remember()
            root.destroy()
            return
        else:
            return
        self.apply_changes()

    def apply_changes(self):
        subprocess.run(['redshift',
                        '-O', str(self.data.temperature),
                        '-b', str(self.data.brightness / 100)])

    def invert_colors(self):
        subprocess.run(['xcalib', '-i', '-a'])

    def decrease_brightness(self):
        self.data.brightness = self.data.brightness - 3

    def increase_brightness(self):
        self.data.brightness = self.data.brightness + 3
        if self.data.brightness > 100:
            self.data.brightness = 100

    def decrease_temperature(self):
        # make more red
        # https://en.wikipedia.org/wiki/Color_temperature
        self.data.temperature = self.data.temperature - 100

    def increase_temperature(self):
        # make more blue
        # https://en.wikipedia.org/wiki/Color_temperature
        self.data.temperature = self.data.temperature + 100

    def remember(self):
        with open(get_absolute_path('pickle_file'), 'wb') as pickle_file:
            pickle.dump(self.data, pickle_file)


def get_absolute_path(relative_path):
    this_file_path = os.path.realpath(__file__)
    this_file_directory = os.path.dirname(this_file_path)
    absolute_path = os.path.join(this_file_directory, relative_path)
    return absolute_path


class Hints:
    def __init__(self):
        self.label = tkinter.Label(root, text='''Controls:
brighter b,k
darker   d,j
warmer   w,h
colder   c,l
bright   1,o,f
invert   i
reset    r''')
        self.label.pack()
        

class Default:
    def __init__(self):
        self.brightness = 100
        self.temperature = 3500 
 

root = tkinter.Tk()
logic = Logic()
root.bind('<Key>', logic.handle_key)
root.title('set_screen')
root.attributes('-type', 'dialog')
hints = Hints()
root.mainloop()
