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

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

    def get_lyric(self, max_length = 17):
        lyrics = open("lyrics.txt", "r").readlines()
        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_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
