# -*- coding: utf-8 -*-
"""Simple script to run Idle from a venv in PyCharm."""
import os
import subprocess
import sys
from tkinter import (
    Frame, Label, Button, mainloop
)

try:
    # Import for Python pre 3.6
    from idlelib.PyShell import main
except ModuleNotFoundError:
    # Import for Python version 3.6 and later
    from idlelib.pyshell import main # noqa


def principal():
    LOCAL_DEFAULT_LINUX = "/home/luxu/Desktop/fpython/"
    if os.name != "posix":  # windows
        homepath = os.path.expanduser(os.getenv("USERPROFILE"))
        desktoppath = "Desktop"
        LOCAL_DEFAULT_WINDOWS = os.path.join(homepath, desktoppath, "fpython/")

    class Application(Frame):
        def __init__(self, master=None):

            Frame.__init__(self, master)
            top = Frame()
            top.pack(fill="both", expand=True)
            self.f = Frame(top)
            self.f.pack(fill="x")
            rotulo = Label(self.f, text="Scripts", foreground="white")
            rotulo.pack()
            rotulo.configure(
                relief="ridge", font="Arial 26 bold", border=5, background="black"
            )
            list_bts = (
                "holerite",
                "calcular_rabbit_ganhos",
                "bd",
                "vivo",
                "registrar_ponto",
                "ImageToText/read_image_to_text",
            )

            for bt in list_bts:
                bt = self.bt(bt)
                bt.configure(relief="groove", border=10, font="Times 20 bold")
                bt.pack(side="left", fill="both", expand=True)

        def run(self, cmd):
            proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            stdout, stderr = proc.communicate()
            return proc.returncode, stdout, stderr

        def comando(self, texto):
            if os.name != "posix":  # windows
                separate_dir_file = texto.split('/')
                if len(separate_dir_file) > 1:
                    path_run_scrips = os.path.join(
                        LOCAL_DEFAULT_WINDOWS, separate_dir_file[0], separate_dir_file[1] + ".py"
                    )
                else:
                    path_run_scrips = f"{LOCAL_DEFAULT_WINDOWS}{texto}.py"
                code, out, err = self.run(
                    [sys.executable, path_run_scrips]
                )
                print(f'CODE..:{code}\n..OUT..:{out}\n..ERR..:{err}')
            else:
                code, out, err = self.run(
                    [sys.executable, f"{LOCAL_DEFAULT_LINUX}{texto}.py"]
                )

        def bt(self, texto):
            return Button(text=f"{texto.capitalize()}", command=lambda: self.comando(texto))

    app = Application()
    app.master.title("Painel de Controle")
    mainloop()


if __name__ == '__main__':
    principal()
