from PIL import Image,ImageDraw,ImageFont
from random import randint, choice
import time
import os

class Sheogorath:
    def __init__(self):
        self.width = 122
        self.height = 250
        script_dir = os.path.dirname(os.path.dirname((os.path.abspath(__file__))))
        res_dir = os.path.join(script_dir, "res")
        print(res_dir)
        try:
            self.lyrics = open(os.path.join(res_dir, "lyrics.txt"), "r").readlines()
        except FileNotFoundError:
            self.lyrics = ["Lyrics not found"]
        try:
            self.sheo = Image.open(os.path.join(res_dir, "sheo1.bmp"))
        except FileNotFoundError:
            self.sheo = Image.new('1', (122, 122))
        try:
            self.font15 = ImageFont.truetype(os.path.join(res_dir, "Font.ttc"), 15)
            self.font24 = ImageFont.truetype(os.path.join(res_dir, "Font.ttc"), 24)
        except FileNotFoundError:
            self.font15 = None
            self.font24 = None

    def get_lyric(self, max_length = 17):
        lyric = choice(self.lyrics)
        out_lyric = ""
        counter = 0
        for word in lyric.split(" "):
            if counter + len(word) < max_length:
                counter += len(word) + 1
                out_lyric += word + " "
            else:
                counter = len(word) + 1
                out_lyric += "\n" + word + " "
        return out_lyric

    def get_lyric_frame(self):
        time_image = Image.new('1', (self.height, self.width), 255)
        time_draw = ImageDraw.Draw(time_image)
        x = randint(0, 40)
        lyric = self.get_lyric((300-x)//15)
        time_image.paste(self.sheo, (x,randint(0, 10)))
        time_draw.rectangle((160, 90, 250, 122), fill = 255)
        if self.font15 and self.font24:
            time_draw.text((185, 90), time.strftime('%H:%M'), font = self.font24, fill = 0)
            time_draw.text((100+x, 5), lyric, font = self.font15, fill = 0)
        return time_image

    def get_stat_frame(self):
        # TODO: Get some stats from statcollector and render into a frame
        return Image.new('1', (self.height, self.width), 255)

    def get_frame(self):
        if randint(0,1):
            return self.get_lyric_frame()
        else:
            return self.get_stat_frame()
