from time import sleep
from my_logger import Log
import io
import os
import sys
import traceback
import settings
import subprocess
from openpyxl import load_workbook
import tkinter
from tkinter import ttk
from tkinter import messagebox


log = Log("main")

class App(tkinter.Tk):
    def __init__(self, *args, **kwargs):
        self.data = load_workbook(log.exec_dir+"/data.xlsx")
        self.sheetnames = self.data.sheetnames

        log.info(self.sheetnames)

        tkinter.Tk.__init__(self, *args, **kwargs)
        self.grid()
        lbl = ttk.Label(self, text="ВВЕДИТЕ КОД НУЖНОЙ ЗАПИСИ", font="Helvetica 32 bold",padding=10).grid(column=0, row=0)
        
        self.command=tkinter.StringVar()

        self.entry = ttk.Entry(self, textvariable=self.command, font="Helvetica 32")
        self.entry.grid(column=1, row=0)
        self.entry.focus()

        self.bind("<Return>", self.handle_command)
        self.bind("<Escape>", self.handle_esc)

    def handle_command(self, arg):
        log.info(self.command.get())
        log.info(arg)
                

        for name in self.sheetnames:
            sheet = self.data.get_sheet_by_name(name)
            log.info("find in: " + sheet.title)
            for cellObj in sheet["A2:A"+str(sheet.max_row)]:
                for cell in cellObj:
                    # log.info(str(cell.value) + " - " + self.command.get())
                    if (str(cell.value)==self.command.get()):
                        log.info("value '{}' finded by row '{}'. coordinate: {}"
                        .format(cell.value, cell.row, cell.coordinate))
                        
                        file_media_name = sheet.cell(row=cell.row, column=3).value
                        log.info(file_media_name)

                        command = "vlc " + file_media_name
                        log.info(command)
                        app.destroy()
                        os.system.__call__(command)
                        return
            log.info("Запись не найдена")
        
        messagebox.showwarning("ВНИМАНИЕ", 
            "ЗАПИСЬ ПО КОМАНДЕ '{}' НЕ НАЙДЕНА".format(self.command.get()))
        self.command.set("")
        
    def handle_esc(self, arg):
        log.info(arg)
        app.destroy()


try:
    app = App()
    app.mainloop()
except Exception as e:
    log.error(log.get_line())
    sys.exit()