"""
* Author: "PepDebian(peppermintosteam@proton.me)
*
* License: SPDX-License-Identifier: GPL-3.0-or-later
*
* This is for the Hub GUI
"""
import tkinter as tk
import tkinter.ttk as ttk
import sqlite3
import subprocess
import os
from tendo import singleton
import bsconf
import hubconf
import putilities
import actions

# setting up window
pehub = bsconf.bbstyle
WINDOW_HEIGHT = 550
WINDOW_WIDTH = 840
pehub.resizable(False, False)
pehub.title('Peppermint Hub')
pehub.tk.call('wm', 'iconphoto', pehub._w,
              tk.PhotoImage(
                  file='/usr/share/pixmaps/peppermint-hub.png'))

# data connection srting
conn = sqlite3.connect('/opt/pypep/dbpep/welval.db')
pcur = conn.cursor()
# Create the table if it does not exist
pcur.execute(
    """ CREATE TABLE IF NOT EXISTS hbchk
              ( id integer PRIMARY KEY AUTOINCREMENT, hstat text); """
)
conn.commit()
conn.close()


def center_screen():
    """ gets the coordinates of the center of the screen """
    screen_width = pehub.winfo_screenwidth()
    screen_height = pehub.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))
    pehub.geometry("{}x{}+{}+{}".format(WINDOW_WIDTH,
                   WINDOW_HEIGHT, x_cordinate, y_cordinate))


def newrech():
    """ see if there is a record in the table, if the table is empty
    then make a new record and set the hstat value off
    """
    data_base = sqlite3.connect('/opt/pypep/dbpep/welval.db')
    hbcur = data_base.cursor()
    hbcur.execute("SELECT COUNT(*) FROM hbchk LIMIT 1")
    hbckempty = hbcur.fetchall()
    if hbckempty[0][0] == 0:
        newrec = """  INSERT INTO hbchk(hstat) VALUES ('off'); """
        hbcur.execute(newrec)
        data_base.commit()
        data_base.close()


def runxd():
    """Run the bash"""
    cmd = "xfce4-terminal -e 'bash -c \"sudo /opt/pypep/xDaily -i\"' --title='xDaily by PeppermintOS' --icon=/opt/pypep/xd.png"
    subprocess.Popen(cmd, shell=True)


def dconfinstallstat():
    """Check to see if is installed if it sis set location"""
    if putilities.install_check('dconf-editor'):
        lbldconf.grid(row=3, column=1, ipadx=2, ipady=2, padx=2, pady=2)
        btdconf.grid(row=2, column=1, ipadx=2, ipady=2, padx=2, pady=2)


# makes sure only a single instance is running
me = singleton.SingleInstance()
X = 1
# Frame that manages system tools
gfr = tk.Frame(pehub)
gfr.grid(row=0, column=0, columnspan=2, ipadx=5, ipady=5, padx=10, pady=5)

# Border fram for system tools
gfs = ttk.Labelframe(gfr, bootstyle="warning", text="General System Tools")
gfs.grid(row=0, column=0)

# frame that manages the software tools
sfr = tk.Frame(pehub)
sfr.grid(
    row=0,
    column=3,
    columnspan=2,
    ipadx=5,
    ipady=5,
    padx=10,
    pady=5,
    sticky='n')

# Border frame for software
sfs = ttk.Labelframe(sfr, bootstyle="warning", text="Software Tools")
sfs.grid(row=0, column=0)


###########################
###General System Tools####
###Start###################
btnnc = ttk.Button(
    gfs,
    text="Network",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.nc,
    command=actions.nhnm)
btnpr = ttk.Button(
    gfs,
    text="Printers",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.pr,
    command=actions.nhpr)
btndu = ttk.Button(
    gfs,
    text="DU",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.du,
    command=actions.ssdu)
btnug = ttk.Button(
    gfs,
    text="UG",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.ug,
    command=actions.ssug)
btnde = ttk.Button(
    gfs,
    text="DE",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.de,
    command=actions.odeconf)
btnpa = ttk.Button(
    gfs,
    text="PA",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.pa,
    command=actions.nhpav)
btnxd = ttk.Button(
    gfs,
    text="XD",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.xd,
    command=runxd)
btnsi = ttk.Button(
    gfs,
    text="SI",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.si,
    command=actions.ssum)
btnum = ttk.Button(
    gfs,
    text="UM",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.um,
    command=actions.sssi)
btnxf = ttk.Button(
    gfs,
    text="XF",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.xf,
    command=actions.osettingsmgr)
btntc = ttk.Button(
    gfs,
    text="TC",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.tc,
    command=actions.lttkcreate)
lblnc = ttk.Label(gfs, text=hubconf.lnc)
lblpr = ttk.Label(gfs, text=hubconf.lpr)
lbldu = ttk.Label(gfs, text=hubconf.ldu)
lblde = ttk.Label(gfs, text=hubconf.lde)
lblug = ttk.Label(gfs, text=hubconf.lug)
lblpa = ttk.Label(gfs, text=hubconf.lpa)
lblxd = ttk.Label(gfs, text=hubconf.lxd)
lblhb = ttk.Label(gfs, text=hubconf.lhb)
lblsi = ttk.Label(gfs, text=hubconf.lsi)
lblum = ttk.Label(gfs, text=hubconf.lum)
lblxf = ttk.Label(gfs, text=hubconf.lxf)
lbltc = ttk.Label(gfs, text=hubconf.ltc)
btnnc.grid(
    row=0,
    column=0,
    ipadx=10,
    ipady=10,
    padx=10,
    pady=10,
    sticky='nesw')
lblnc.grid(row=1, column=0)
btnpr.grid(
    row=0,
    column=1,
    ipadx=10,
    ipady=10,
    padx=10,
    pady=10,
    sticky='nesw')
lblpr.grid(row=1, column=1)
btndu.grid(
    row=0,
    column=2,
    ipadx=10,
    ipady=10,
    padx=10,
    pady=10,
    sticky='nesw')
lbldu.grid(row=1, column=2)
lblhb.grid(row=3, column=0)
btnsi.grid(
    row=2,
    column=1,
    ipadx=10,
    ipady=10,
    padx=10,
    pady=10,
    sticky='nesw')
lblsi.grid(row=3, column=1)
btnug.grid(
    row=2,
    column=2,
    ipadx=10,
    ipady=10,
    padx=10,
    pady=10,
    sticky='nesw')
lblug.grid(row=3, column=2)

btnpa.grid(
    row=4,
    column=0,
    ipadx=10,
    ipady=10,
    padx=10,
    pady=10,
    sticky='nesw')
lblpa.grid(row=5, column=0, padx=0, pady=5)
btnum.grid(
    row=4,
    column=1,
    ipadx=10,
    ipady=10,
    padx=10,
    pady=10,
    sticky='nesw')
lblum.grid(row=5, column=1, padx=0, pady=5)
btnxf.grid(
    row=4,
    column=2,
    ipadx=10,
    ipady=10,
    padx=10,
    pady=10,
    sticky='nesw')
lblxf.grid(row=5, column=2, padx=0, pady=5)

btntc.grid(
    row=6,
    column=0,
    ipadx=10,
    ipady=10,
    padx=10,
    pady=10,
    sticky='nesw')
lbltc.grid(row=7, column=0, padx=0, pady=5)
btnde.grid(
    row=6,
    column=1,
    ipadx=10,
    ipady=10,
    padx=10,
    pady=10,
    sticky='nesw')
lblde.grid(row=7, column=1)
btnxd.grid(
    row=6,
    column=2,
    ipadx=10,
    ipady=10,
    padx=10,
    pady=10,
    sticky='nesw')
lblxd.grid(row=7, column=2)


###########################
###General System Tools####
###End#####################


def hbon():
    """ Turn on hblock """
    data_base = sqlite3.connect('/opt/pypep/dbpep/welval.db')
    uphbon = """ UPDATE hbchk SET hstat = 'on';"""
    updcur = data_base.cursor()
    updcur.execute(uphbon)
    data_base.commit()
    data_base.close()
    btnhboff = ttk.Button(
        gfs,
        text="hboff",
        cursor="hand2",
        bootstyle="dark-outline",
        image=hubconf.hboff,
        command=hbon)
    btnhboff.lower()
    btnhbon = ttk.Button(
        gfs,
        text="hbon",
        cursor="hand2",
        bootstyle="dark-outline",
        image=hubconf.hbon,
        command=hboff)
    btnhbon.grid(
        row=2,
        column=0,
        ipadx=10,
        ipady=10,
        padx=10,
        pady=10,
        sticky='nesw')
    cmd = "xfce4-terminal -e 'bash -c \"hblock  exit 0\";bash'"
    subprocess.Popen(cmd, shell=True)


def hboff():
    """ Turn off hblock """
    data_base = sqlite3.connect('/opt/pypep/dbpep/welval.db')
    uphbof = """ UPDATE hbchk SET hstat = 'off';"""
    updocur = data_base.cursor()
    updocur.execute(uphbof)
    data_base.commit()
    data_base.close()
    btnhbon = ttk.Button(
        gfs,
        text="hbon",
        cursor="hand2",
        bootstyle="dark-outline",
        image=hubconf.hbon,
        command=hboff)
    btnhbon.lower()
    btnhboff = ttk.Button(
        gfs,
        text="hboff",
        cursor="hand2",
        bootstyle="dark-outline",
        image=hubconf.hboff,
        command=hbon)
    btnhboff.grid(
        row=2,
        column=0,
        ipadx=10,
        ipady=10,
        padx=10,
        pady=10,
        sticky='nesw')
    cmd = "xfce4-terminal -e 'bash -c \"hblock -S none -D none exit 0\";bash'"
    subprocess.Popen(cmd, shell=True)


###########################
######Software Start#######
###########################
btnsp = ttk.Button(
    sfs,
    text="sp",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.sp,
    command=actions.packages)
btnkm = ttk.Button(
    sfs,
    text="km",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.km,
    command=actions.lkumo)
btnah = ttk.Button(
    sfs,
    text="ah",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.ah,
    command=actions.ssai)
btnsc = ttk.Button(
    sfs,
    text="sc",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.sc,
    command=actions.ssspm)
btnss = ttk.Button(
    sfs,
    text="ss",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.ss,
    command=actions.ssst)
btnsw = ttk.Button(
    sfs,
    text="ss",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.ss,
    command=actions.ssss)
btngs = ttk.Button(
    sfs,
    text="gs",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.gs,
    command=actions.ssgn)
btngsw = ttk.Button(
    sfs,
    text="gsw",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.gs,
    command=actions.ssgns)
btnfp = ttk.Button(
    sfs,
    text="fp",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.fp,
    command=actions.ssfh)
btnps = ttk.Button(
    sfs,
    text="ps",
    cursor="hand2",
    bootstyle="dark-outline",
    image=hubconf.ps,
    command=actions.lpscope)
lblps = ttk.Label(sfs, text=hubconf.lps)

lblsp = ttk.Label(sfs, text=hubconf.lsp)
lblkm = ttk.Label(sfs, text=hubconf.lkm)
lblah = ttk.Label(sfs, text=hubconf.lah)
lblsc = ttk.Label(sfs, text=hubconf.lsc)
lblss = ttk.Label(sfs, text=hubconf.lss)
lblsw = ttk.Label(sfs, text=hubconf.lssw)
lblgs = ttk.Label(sfs, text=hubconf.lgs)
lblgsw = ttk.Label(sfs, text=hubconf.lgsw)
lblfp = ttk.Label(sfs, text=hubconf.lfp)
lblmfr = ttk.Label(sfs, text=hubconf.lmf, wraplength=400)
lblmfr.grid(row=4, column=0, columnspan=4, ipadx=5, ipady=5, padx=5, pady=5)
btnsp.grid(
    row=0,
    column=0,
    ipadx=10,
    ipady=10,
    padx=10,
    pady=10,
    sticky='nesw')
lblsp.grid(row=1, column=0)
btnkm.grid(
    row=0,
    column=1,
    ipadx=10,
    ipady=10,
    padx=10,
    pady=10,
    sticky='nesw')
lblkm.grid(row=1, column=1)
btnah.grid(
    row=0,
    column=2,
    ipadx=10,
    ipady=10,
    padx=10,
    pady=10,
    sticky='nesw')
lblah.grid(row=1, column=2)
btnsc.grid(
    row=0,
    column=3,
    ipadx=10,
    ipady=10,
    padx=10,
    pady=10,
    sticky='nesw')
lblsc.grid(row=1, column=3)


###Functions needed for the software sorting###
def sethblockbtn():
    """ check hblock stat """
    dbhb = sqlite3.connect('/opt/pypep/dbpep/welval.db')
    hbofn = dbhb.cursor()
    hbofn.execute("SELECT COUNT(*) FROM hbchk WHERE hstat ='on'")
    hbresult = hbofn.fetchone()
    dbhb.commit()
    if int(hbresult[0]) > 0:
        btnhbon = ttk.Button(
            gfs,
            text="hbon",
            cursor="hand2",
            bootstyle="dark-outline",
            image=hubconf.hbon,
            command=hboff)
        btnhbon.grid(
            row=2,
            column=0,
            ipadx=10,
            ipady=10,
            padx=10,
            pady=10,
            sticky='nesw')
    else:
        btnhboff = ttk.Button(
            gfs,
            text="hboff",
            cursor="hand2",
            bootstyle="dark-outline",
            image=hubconf.hboff,
            command=hbon)
        btnhboff.grid(
            row=2,
            column=0,
            ipadx=10,
            ipady=10,
            padx=10,
            pady=10,
            sticky='nesw')


def gnmhandle():
    """if gnome store is installed, link the applicaton, otherwise
       link to their website cache['gnome-software'].is_installed:
    """
    if putilities.install_check('gnome-software'):
        btngs.grid(
            row=2,
            column=0,
            ipadx=10,
            ipady=10,
            padx=10,
            pady=10,
            sticky='nesw')
        lblgs.grid(row=3, column=0, padx=0, pady=5)
    else:
        btngsw.grid(
            row=2,
            column=0,
            ipadx=10,
            ipady=10,
            padx=10,
            pady=10,
            sticky='nesw')
        lblgsw.grid(row=3, column=0, padx=0, pady=5)


def fphandle():
    """if FlatPak is installed, open the gnome store otherwise open
       flathub cache['flatpak'].is_installed:
    """
    if putilities.install_check('flatpak'):
        # If the Gnome store is installed dont show the Flatpak button
        # If it is NOT installed Show the flatpak button
        btnps.grid(
            row=2,
            column=2,
            ipadx=10,
            ipady=10,
            padx=10,
            pady=10,
            sticky='nesw')
        lblps.grid(row=3, column=2)

        if putilities.install_check('gnome-software'):
            btnfp.destroy()
            lblfp.destroy()
        else:
            lblfp.grid(row=3, column=1, padx=0, pady=5)
            btnfp.grid(
                row=2,
                column=1,
                ipadx=10,
                ipady=10,
                padx=10,
                pady=10,
                sticky='nesw')
    else:
        lblfp.grid(row=3, column=1, padx=0, pady=5)
        btnfp.grid(
            row=2,
            column=1,
            ipadx=10,
            ipady=10,
            padx=10,
            pady=10,
            sticky='nesw')
        # setPscope button pos
        btnps.grid(
            row=2,
            column=3,
            ipadx=10,
            ipady=10,
            padx=10,
            pady=10,
            sticky='nesw')
        lblps.grid(row=3, column=3)


def sbphandle():
    """if snap is installed, open app, otherwise make a button to the snap store"""
    if putilities.install_check('snapd'):  # cache['snapd'].is_installed:
        btnsw.destroy()
        lblsw.destroy()
        if putilities.install_check('gnome-software'):
            btnss.grid(
                row=2,
                column=1,
                ipadx=10,
                ipady=10,
                padx=10,
                pady=10,
                sticky='nesw')
            lblss.grid(row=3, column=1, padx=0, pady=5)
    else:
        if putilities.install_check('gnome-software'):
            lblss.destroy()
            btnss.destroy()
            btnsw.grid(
                row=2,
                column=1,
                ipadx=10,
                ipady=10,
                padx=10,
                pady=10,
                sticky='nesw')
            lblsw.grid(row=3, column=1, padx=0, pady=5)
        else:
            btnsw.grid(
                row=2,
                column=2,
                ipadx=10,
                ipady=10,
                padx=10,
                pady=10,
                sticky='nesw')
            lblsw.grid(row=3, column=2, padx=0, pady=5)


def debianbase():
    """Bring functions together"""
    fphandle()
    gnmhandle()
    sbphandle()


def devuanbase():
    """set up for a Devuan Build"""
    lblss.destroy()
    btnss.destroy()
    btnfp.grid(
        row=2,
        column=1,
        ipadx=10,
        ipady=10,
        padx=10,
        pady=10,
        sticky='nesw')
    lblfp.grid(row=3, column=1, padx=0, pady=5)
    fphandle()
    btnps.grid(
        row=2,
        column=2,
        ipadx=10,
        ipady=10,
        padx=10,
        pady=10,
        sticky='nesw')
    lblps.grid(row=3, column=2)
    gnmhandle()


def vdecide():
    """Decide Version logo to use"""
    if os.path.exists("/etc/devuan_version"):
        devuanbase()
    elif os.path.exists("/etc/debian_version"):
        debianbase()


# call Center screen
center_screen()
# start the version process
vdecide()
# set the block status
sethblockbtn()
# run the applictaion
pehub.mainloop()
