"""I provide a simple bit viewer specialized for AMMOS files."""

import tkinter as tk
from PIL import Image, ImageTk
from random import randbytes

class MainApplication(tk.Frame):
    """I implement a simple bit viewer specialized for AMMOS files."""

    def __init__(self, parent):
        """I create the application window."""
        super().__init__(parent)

        self.parent = parent
        self.file_name = "../sample_data/audio_data_sample.bin"
        self.file = open(self.file_name, 'rb')
        self.bytes = self.file.read(2116*50)
        self.cycle = 2116
        self.cache = 500000000
        self.offset = 0
        self.buildup()

    def buildup(self):
        """I build up the initial user interface."""
        self.parent.title("File name:" + self.file_name + " Size:" + str(len(self.bytes)))
        self.pack(fill="both", expand=True)
        self.default_button_width = 10
        image_frame = tk.Frame(self)
        image_frame.pack(side=tk.LEFT)
        self.canvas = tk.Canvas(image_frame, bg="#000000", width=self.cycle, height=600)
        self.canvas.pack()
        random_bytes = randbytes(480000)
        if len(self.bytes) < 480000:
            random_bytes = self.bytes[self.offset:] + bytearray([0xff] * (480000-len(self.bytes)-self.offset))
        self.image = ImageTk.PhotoImage(Image.frombytes("L", (self.cycle, int(len(random_bytes) / self.cycle)), random_bytes))
        # self.image.show()
        button_frame = tk.Frame(self)
        self.canvas.create_image(0, 0, anchor='nw', image=self.image)
        # image_label. = self.image
        button_frame.pack(side="right")

        tk.Label(button_frame, text='Cycle in bits').pack(side=tk.TOP)
        self.cycle_entry = tk.Entry(button_frame)
        # self.cycle_entry.set()
        self.cycle_entry.pack(side=tk.TOP)

        tk.Label(button_frame, text='Cache in bytes').pack(side=tk.TOP)
        self.cache_entry = tk.Entry(button_frame)
        self.cache_entry.pack(side=tk.TOP)

        tk.Label(button_frame, text='Offset in bits').pack(side=tk.TOP)
        self.offset_entry = tk.Entry(button_frame)
        self.offset_entry.pack(side=tk.TOP)

        tk.Button(
            button_frame,
            text="Load file",
            width=self.default_button_width,
            command=self.load_file).pack(side="top", fill="both", expand=True)

        tk.Button(
            button_frame,
            text="Quit",
            width=self.default_button_width,
            command=self.quit).pack(side="top", fill="both", expand=True)

    def load_file(self):
        pass

    def quit(self):
        self.parent.destroy()


if __name__ == '__main__':
    root = tk.Tk()
    root.geometry("1920x1200")

    app = MainApplication(root)

    root.mainloop()
