"""
* Author: "PepDebian(peppermintosteam@proton.me)
*
* License: SPDX-License-Identifier: GPL-3.0-or-later
*
* Update log from CodeBerg
"""

import json
import sqlite3
import tkinter as tk
import os
import importlib.util
import subprocess
import ttkbootstrap as ttk
from tendo import singleton
import bsconf



# setup the window
pwin = bsconf.bbstyle
WINDOW_HEIGHT = 190
WINDOW_WIDTH = 310
pwin.resizable(False, False)
pwin.title('Peppermint Scope')
pwin.tk.call('wm', 'iconphoto', pwin._w,
             tk.PhotoImage(
                   file='/usr/share/pixmaps/peppermint-old.png'))

# keep only instance at a time
me = singleton.SingleInstance()

# database connection string
conn = sqlite3.connect('/opt/pypep/dbpep/welval.db')
pcur = conn.cursor()
# Create the table
pcur.execute(
    'CREATE TABLE IF NOT EXISTS gitdata ( date text, message text, commitd text)')


def debdata():
    """ Gets the Debian Data"""
    con = sqlite3.connect('/opt/pypep/dbpep/welval.db')
    cur = con.cursor()
    git_data = json.load(open('git-pepd64.json'))
    columns = ['date', 'message', 'commit']
    # set the data up to be binded
    value = []
    values = []
    for data in git_data:
        for i in columns:
            value.append(str(dict(data).get(i)))
        values.append(list(value))
        value.clear()

    # clear the old data
    dquery = 'DELETE FROM gitdata'
    # the query used to store the data
    iquery = 'INSERT INTO gitdata values(?,?,?)'
    # clean out auto updates
    cquery = """ DELETE FROM gitdata WHERE message LIKE 'Auto%' """
    # run the query
    cur.execute(dquery)
    cur.executemany(iquery, values)
    cur.execute(cquery)
    con.commit()
    con.close()
    print("Data is Done")
    # open the results screen
    os.system('python3 /opt/pypep/pddata.py &')


def devdata():
    """Gets the Devuan Data"""
    con = sqlite3.connect('/opt/pypep/dbpep/welval.db')
    cur = con.cursor()
    git_data = json.load(open('git-pepdv64.json'))
    columns = ['date', 'message', 'commit']
    # set the data up to be binded
    value = []
    values = []
    for data in git_data:
        for i in columns:
            value.append(str(dict(data).get(i)))
        values.append(list(value))
        value.clear()
    # clear the old data
    dquery = 'DELETE FROM gitdata'
    # the query used to store the data
    iquery = 'INSERT INTO gitdata values(?,?,?)'
    # clean out auto updates
    cquery = """ DELETE FROM gitdata WHERE message LIKE 'Auto%' """
    # run the query
    cur.execute(dquery)
    cur.executemany(iquery, values)
    cur.execute(cquery)
    # commit the data and close connection
    con.commit()
    con.close()
    print("Data is Done")
    # open the results screen for devuan
    os.system('python3 /opt/pypep/pdvdata.py &')


def peptoolsdata():
    """prepare the log JSON data for peptools"""
    con = sqlite3.connect('/opt/pypep/dbpep/welval.db')
    cur = con.cursor()
    git_data = json.load(open('git-peptools.json'))
    columns = ['date', 'message', 'commit']
    # set the data up to be binded
    value = []
    values = []
    for data in git_data:
        for i in columns:
            value.append(str(dict(data).get(i)))
        values.append(list(value))
        value.clear()
    # clear the old data
    dquery = 'DELETE FROM gitdata'
    # the query used to store the data
    iquery = 'INSERT INTO gitdata values(?,?,?)'
    # clean out auto updates
    cquery = """ DELETE FROM gitdata WHERE message LIKE 'Auto%' """
    # run the query
    cur.execute(dquery)
    cur.executemany(iquery, values)
    cur.execute(cquery)
    # commit the data and close connection
    con.commit()
    con.close()
    print("Data is Done")
    # open the results screen for peptools
    os.system('python3 /opt/pypep/ptdata.py &')


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 instdep():
    """This will pop a terminal so the user ca instal the qtsql"""
    # kill the window
    pwin.destroy()
    # pop the terminal
    cmd = "xfce4-terminal -e 'bash -c \"sudo apt-get install -y python3-pyqt5.qtsql\";bash'"
    subprocess.Popen(cmd, shell=True)


def vdecide():
    """All the buttons and placements"""
    # These are the controls that are used
    btnpt = ttk.Button(
        text="PepTools Updates",
        bootstyle="danger-outline",
        width=27,
        command=peptoolsdata)
    btnid = ttk.Button(
        text="Install Dependencies",
        bootstyle="danger-outline",
        width=27,
        command=instdep)
    btndev = ttk.Button(
        text="Pep Devuan Updates",
        bootstyle="danger-outline",
        width=27,
        command=devdata)
    btndeb = ttk.Button(
        text="Pep Debian Updates",
        bootstyle="danger-outline",
        width=27,
        command=debdata)
    lblex = ttk.Label(
        pwin,
        text="Select what updates you would like to review",
        wraplength=300)
    lbldep = ttk.Label(
        pwin,
        text="PepScope needs some dependencies installed",
        wraplength=300)
    # variables  used to test if package is installed
    package = 'PyQt5.QtSql'
    is_present = importlib.util.find_spec(package)
    # conditions
    if os.path.exists("/etc/devuan_version"):
        if is_present is None:
            print("Is Not Here Devuan!")
            # Button and Label placements
            btnid.grid(row=1, column=1, ipadx=5, ipady=5, padx=5, pady=5)
            lbldep.grid(
                row=0,
                column=0,
                columnspan=4,
                ipadx=5,
                ipady=5,
                padx=5,
                pady=5)
        else:
            print("You Good Devuan!")
            # Button and Label placements
            btndev.grid(row=1, column=1, ipadx=5, ipady=5, padx=5, pady=5)
            btnpt.grid(row=2, column=1, ipadx=5, ipady=5, padx=5, pady=5)
            lblex.grid(
                row=0,
                column=0,
                columnspan=4,
                ipadx=5,
                ipady=5,
                padx=5,
                pady=5)
    elif os.path.exists("/etc/debian_version"):
        if is_present is None:
            print("Is Not Here Debian!")
            # Button and Label placements
            btnid.grid(row=1, column=1, ipadx=5, ipady=5, padx=5, pady=5)
            lbldep.grid(
                row=0,
                column=0,
                columnspan=4,
                ipadx=5,
                ipady=5,
                padx=5,
                pady=5)

        else:
            print("You Good Debian!")
            # Button and Label placements
            btndeb.grid(row=1, column=1, ipadx=5, ipady=5, padx=5, pady=5)
            btnpt.grid(row=2, column=1, ipadx=5, ipady=5, padx=5, pady=5)
            lblex.grid(
                row=0,
                column=0,
                columnspan=4,
                ipadx=5,
                ipady=5,
                padx=5,
                pady=5)


# call Center screen
center_screen()
vdecide()
pwin.mainloop()
