import json
import requests
import time


class Datanose:
    def __init__(self, bot, config):
        self.cmd_list = [self.lb, self.lok]
        self.bot = bot
        self.config = config
        self.url = "https://api.datanose.nl/Rooms"

    
    def float_to_time(self, flt):
        hr = str(int(flt % 24))
        mn = (flt - int(flt)) * 60
        if mn < 10:
            mn = "0" + str(int(mn))
        else:
            mn = str(int(mn))
        return hr + ":" + mn


    def form_sched(self, data, lok):
        msg = f"*Lessen in {lok} op 19-02-2018:*\n"
        for les in sorted(data, key=lambda x: x['StartTime']):
            if les['CourseCode'] != None:
                name = les['CourseName']
                doc = ", ".join(les['Staff'])
                start = self.float_to_time(les['StartTime'])
                end = self.float_to_time(les['StartTime'] + les['Duration'])
                msg += f"_{name}_\ndoor: {doc}\nvan: {start} tot: {end}\n\n"
        return msg


    def get_free(self, room):
        url = self.url + "/" + room + "/"
        date = "2018-02-19"
        resp = requests.get(url, params={'date': date})
        data = resp.json()
        hrs = []
        for les in data:
            hrs.append((les['StartTime'], (les['StartTime'] + les['Duration'])))
        if len(hrs) == 0:
            return [(9.0, 22.0)]
        hrs.sort()
        free = []
        last_e = 9
        for (s, e) in hrs:
            if s != last_e:
                free.append((last_e, s))
            if (s, e) == hrs[-1] and e != 22.0:
                free.append((e, 22.0))
            last_e = e
        return free


    def lok(self, ctx):
        """Geeft het dagrooster van een lokaal"""
        if len(ctx.args) == 0:
            pass
        else:
            room = "SP" + ctx.args[0].upper()
            url = self.url + "/" + room + "/"
            date = "2018-02-19"
            resp = requests.get(url, params={'date': date})
            data = resp.json()
            ctx.message_chan(self.form_sched(data, room))   


    def lb(self, ctx):
        """Toont lokaalbeschikbaarheid"""
        ctx.message_chan("*Lokaalbeschikbaarheid:*\n(dit kan even duren)")
        stream = open("ext/datanose/rooms.json", "r")
        rooms = json.load(stream)
        msg = ""
        for room in rooms:
            if room[0:2] == "SP":
                free = self.get_free(room)
            if room[0:2] == "SP" and len(free) > 0:
                prds = []
                for (s, e) in free:
                    prds.append(f"{self.float_to_time(s)} tot {self.float_to_time(e)}")
                ps = ", ".join(prds)
                msg += f"*{room}* {ps}\n"
        ctx.message_chan(msg)



def setup(bot, config):
    return Datanose(bot, config)

# time.strftime("%Y-%m-%d")
