"""
* Author: "PepDebian(peppermintosteam@proton.me)
*
* License: SPDX-License-Identifier: GPL-3.0-or-later
*
* This is for the Kumo SSB Gui
"""

import os
import sqlite3
import tkinter as tk
import ttkbootstrap as ttk
import bsconf


# setup the window
pwin = bsconf.bbstyle
pwin.resizable(False, False)
WINDOW_HEIGHT = 300
WINDOW_WIDTH = 640
pwin.title('Peppermint Kumo (SSB Manager)')


# Set the user path
gusr = os.getlogin()
spath = "/home/" + gusr + "/.local/share/pmostools/peptools"
# Set the icon
pwin.tk.call('wm', 'iconphoto', pwin,
             tk.PhotoImage(
                   file=spath + '/images/kumosm.png'))
# Set the database connection string
dcon = sqlite3.connect(spath + '/welval.db')
pcur = dcon.cursor()

# Create the table if not exists
pcur.execute(""" CREATE TABLE IF NOT EXISTS kumoapp (id integer PRIMARY
             KEY AUTOINCREMENT, ssbname text, lnk text);"""
             )


def center_screen():
    """ gets the coordinates of the center of the screen """
    screen_width = pwin.winfo_screenwidth()
    screen_height = pwin.winfo_screenheight()
    # Coordinates of the upper left corner of the window to make the window
    # appear in the center
    x_cordinate = int((screen_width / 2) - (WINDOW_WIDTH / 2))
    y_cordinate = int((screen_height / 2) - (WINDOW_HEIGHT / 2))
    pwin.geometry("{}x{}+{}+{}".format(WINDOW_WIDTH,
                                       WINDOW_HEIGHT, x_cordinate, y_cordinate
                                       )
                  )


def add_new_ssb():
    """ Add new ssb """
    ssb_name = ssb_value.get("1.0", 'end-1c')
    ssb_address = urladdr_value.get("1.0", 'end-1c')
    sql_insert = """ INSERT INTO kumoapp(ssbname,lnk) VALUES(?,?);"""
    pcur.execute(sql_insert, (ssb_name, ssb_address,))
    dcon.commit()
    ssb_value.delete('1.0', tk.END)
    urladdr_value.delete('1.0', tk.END)
    os.system('python3 ' +  spath +  '/refresh.py')


def delete_ssb():
    """ Delete the ssb that is selected """
    get_name = cmbo.get()
    link_address = """ DELETE FROM kumoapp WHERE ssbname = ? """
    pcur.execute(link_address, (get_name,))
    dcon.commit()
    runaddr_value.delete('1.0', tk.END)
    pwin.destroy()
    os.system('python3 refresh.py')


def fill_dropdown():
    """set the combobox value"""
    cursor = dcon.execute('SELECT ssbname FROM kumoapp')
    result = []
    for row in cursor.fetchall():
        result.append(row[0])
    return result


def fill_url_address():
    """ get the url of the ssb and run the it in lua"""
    get_name = cmbo.get()
    link_address = """ SELECT lnk FROM kumoapp WHERE ssbname = ? """
    pcur.execute(link_address, (get_name,))
    use_address = pcur.fetchone()
    runaddr_value.delete('1.0', tk.END)
    runaddr_value.insert("end-1c", use_address)
    run_addrs = runaddr_value.get("1.0", 'end-1c')
    os.system('luakit -U ' + run_addrs + ' &')

### Create SSB side


new_label = ttk.Label(pwin, text="Create new SSBs",
                      bootstyle="danger",
                      font=("Helvetica", 14)
                      )

new_label.place(x=10, y=20)

ssb_label = ttk.Label(pwin, text="Give the ssb a name:")
ssb_label.place(x=10, y=50)
ssb_value = tk.Text(pwin, height=1, width=25)
ssb_value.place(x=10, y=75)

separator = ttk.Separator(pwin, orient='vertical')
separator.place(relx=.495, rely=0, relheight=1)

urladdr_label = ttk.Label(pwin, text="Enter the Url:")
urladdr_label.place(x=10, y=125)
urladdr_value = tk.Text(pwin, height=4, width=30)
urladdr_value.place(x=10, y=150)

btnsv = ttk.Button(
    pwin,
    text="save",
    cursor="hand2",
    bootstyle="light-outline",
    width=5,
    command=add_new_ssb
    )
btnsv.place(x=10, y=250)

### Manage SSBs side)
manage_label = ttk.Label(pwin, text="Manage SSBs",
                         bootstyle="danger",
                         font=("Helvetica", 14)
                         )
manage_label.place(x=340, y=20)

lblcmbo = ttk.Label(pwin, text="Select SSB to Manage:")
lblcmbo.place(x=340, y=50)
cmbo = ttk.Combobox(pwin)
cmbo.place(x=340, y=70)
cmbo['values'] = (fill_dropdown())

runaddr_label = ttk.Label(pwin, text="Url Address:")
runaddr_label.place(x=340, y=125)
runaddr_value = tk.Text(pwin, height=4, width=30)
runaddr_value.place(x=340, y=150)

btnrun = ttk.Button(
    pwin,
    text="Run",
    cursor="hand2",
    bootstyle="light-outline",
    width=7,
    command=fill_url_address
    )
btnrun.place(x=340, y=250)

btndelete = ttk.Button(
    pwin,
    text="Delete",
    cursor="hand2",
    bootstyle="light-outline",
    width=7,
    command=delete_ssb
    )
btndelete.place(x=430, y=250)

center_screen()
pwin.mainloop()
