import time
import tkinter as tk

from PIL import Image, ImageTk


class Splash(tk.Toplevel):
    def __init__(self, master=None, **kw):
        tk.Toplevel.__init__(self, master=master, **kw)
        self._root = master
        _image = Image.open('gui/img/splash.png')
        self._image = ImageTk.PhotoImage(_image)

        self._root.withdraw()

        tk.Label(self, image=self._image, relief='flat').pack()

        self.center()
        self.lift()
        self.attributes('-topmost', True)
        self.attributes('-topmost', False)

        self.overrideredirect(1)
        self.update()

        time.sleep(3)

        self.destroy()

        self._root.deiconify()

    def center(self):
        """
        centers a tkinter window
        :param self: the root or Toplevel window to center
        """
        self.update_idletasks()
        width = self.winfo_width()
        frm_width = self.winfo_rootx() - self.winfo_x()
        win_width = width + 2 * frm_width
        height = self.winfo_height()
        titlebar_height = self.winfo_rooty() - self.winfo_y()
        win_height = height + titlebar_height + frm_width
        x = self.winfo_screenwidth() // 2 - win_width // 2
        y = self.winfo_screenheight() // 2 - win_height // 2
        self.geometry('{}x{}+{}+{}'.format(width, height, x, y))
        self.deiconify()
