#!/usr/bin/env python
from phue import Bridge
import sys, os
import json
from PhilipsHue import *
import argparse

class Hue(Lights, Groups, TimeRules):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def keys(self):
        return list(self.conn.get_api().keys())

class main:
    def __init__(self, *args, **kwargs):
        self.TimeRules = TimeRules()
        self.LoadSettings()
        self.LoadArgs()
        self.UpdateLights()
        self.UpdateColor()
        self()

    def __call__(self, *args, **kwargs):
        if self.color:
            hue.SetColor(int(self.color), *self.lights)
        elif self.on:
            hue.LightsOn(*self.lights)
        elif self.off:
            hue.LightsOff(*self.lights)
        elif self.switch:
            hue.SwitchLight(*self.lights)
        elif self.get_temperature:
            print(*self.lights)

        # Prints brightness of given light.
        elif self.get_brightness:
            for light in self.lights:
                try:
                    print(f"{light}: {hue.GetBrightness(light)}")
                except KeyError:
                    pass

        elif self.dim:
            hue.DimBrightness(self.dim, *self.lights)
        elif self.increase:
            hue.IncreaseBrightness(self.increase, *self.lights)

        elif self.list:
            for key, value in self.areas.items():
                print(f"{key}: {value}")

        else:
            self.Auto()

    def __setitem__(self, key, value):
        if key in self.__dict__.keys():
            print(f"{key} is a duplicate")
        self.__dict__[key] = value

    def Auto(self):
        """
        Automatic rules based on TimeRules class in checktime.py. 
        Allows to execute main program with no arguments for estimated values of color temperature and brightness.
        """
        for area, lights in self.areas.items():
            for light in lights:
                if self.TimeRules.brightness:
                    hue.LightsOn(light)
                    hue.SetColor(self.TimeRules.temperature, light)
                    hue.SetBrightness(self.TimeRules.brightness, light)
                else:
                    hue.LightsOff(light)

    def LoadSettings(self):
        global hue
        settingsfile = os.path.dirname(__file__) + "/PhilipsHue/settings.json"
        settings = json.load(open(settingsfile, "r"))
        for key, value in settings.items():
            self[key] = value
        hue = Hue(**settings)

    def LoadArgs(self):
        args = Arguments()
        for key, value in args.data.items():
            self[key] = value

    def UpdateLights(self):
        new = []
        if "all" in self.__dict__.keys() and self.all:
            for key, value in self.areas.items():
                new.extend(value)
        else:
            if self.lights:
                for i in range(len(self.lights)):
                    if self.lights[i] in self.areas.keys():
                        new.extend(self.areas[self.lights[i]])
        self.lights = new

    def UpdateColor(self):
        if self.color in self.colors.keys():
            self.color = self.colors[self.color]

if __name__ == "__main__":
    main()