# -*- coding: utf-8 -*-

import gettext
import rpm
import os
import subprocess
from PyQt6.QtCore import Qt, QObject, pyqtSlot, QAbstractListModel, QModelIndex, QCoreApplication, pyqtSignal
from PyQt6.QtNetwork import QNetworkInformation
from PyQt6.QtWidgets import QStyledItemDelegate,QLabel
from xdg.DesktopEntry import DesktopEntry
import netifaces

translate = QCoreApplication.translate

def get_desktop_name(x):
  return {
    '01plasma':'KDE Plasma',
    '02GNOME':'Gnome',
    'gnome': 'Gnome Wayland',
    'gnome-xorg': 'Gnome X.org',
    'LXDE':'LXDE',
    'MATE':'Mate',
    'Cinnamon':'Cinnamon',
    '23E17':'Enlightenment',
    '07IceWM':'IceWM',
    '26Openbox':'Openbox',
    '03WindowMaker':'WindowMaker',
    '09Fvwm2':'Fvwm2',
  }.get(x,'Other')

def get_desktop_name2(x):
  return {
      'KDE':'KDE Plasma',
      'XFCE':'Xfce',
      'LXQt':'LXQt',
      'MATE':'Mate',
      'GNOME':'Gnome',
      'X-Cinnamon':'Cinnamon',
    }.get(x,'unknown')
  

def is_installed(name):
    mi = rpm.TransactionSet().dbMatch('name', name)
    release = ""
    for h in mi:
        release = (h['release'])
    if release.endswith("tainted"):
        repo = 'tainted'
    elif release.endswith("nonfree"):
        repo = 'nonfree'
    else:
        repo = '' 
    return release != "", repo


class Launcher(QObject):
    installed = pyqtSignal()
    needed = pyqtSignal(str, arguments=["repo"])
    repo = pyqtSignal()
    noprogram = pyqtSignal()

    def __init__(self):
        QObject.__init__(self)


class Autostart():
    def __init__(self):
        self.home = os.getenv("HOME")
        self.desktop_file = os.path.join(self.home, ".config", "autostart", "mageiawelcome.desktop")
        self.desktop_file_system = "/etc/xdg/autostart/mageiawelcome.desktop"

    def disable(self):
        if os.path.exists(self.desktop_file):
            desktop = DesktopEntry(self.desktop_file)
        else:
            os.makedirs(os.path.dirname(self.desktop_file), exist_ok=True)
            desktop = DesktopEntry(self.desktop_file_system)
        desktop.set('Hidden', 'true')

        # Store modified file
        desktop.write(filename=self.desktop_file)

    def enable(self):
        # desktop in autostart is already installed in /etc we remove the local one to avoid to hide system one
        if os.path.exists(self.desktop_file):
            os.remove(self.desktop_file)

    def isEnabled(self):
        if os.path.exists(self.desktop_file):
            desktop = DesktopEntry(self.desktop_file)
            return not desktop.getHidden()
        else:
            return True
        
class NetworkState(QObject):
    def __init__(self):
        QObject.__init__(self)
        QNetworkInformation.load(QNetworkInformation.Feature.Reachability)
        self.net = QNetworkInformation.instance()
    
    @pyqtSlot(result=bool)
    def isOffLine(self):
        # Search active network connections
        # QNetworkInformation::Reachability::Online	4	Indicates that the system is connected to a network and able to access the Internet.
        return not self.net.reachability() == 4

    def reachability(self):
        return self.net.reachability()

    def availableBackends(self):
        net_list = netifaces.interfaces()
        if "lo" in net_list:
            net_list.remove("lo")
        return net_list


class ConfList():

    def __init__(self, ns, parent=None):
        # Changing working directory
        abspath = os.path.abspath(__file__)
        dname = os.path.dirname(abspath)
        os.chdir(dname)
        self.net_state = ns

        # collect sys info
        release = subprocess.getoutput("lsb_release -sd")
        release = release[1:-1]
        release_nb = subprocess.getoutput("lsb_release -sr")
        release_nb = release_nb.strip()
        kernel = subprocess.getoutput("uname -r")
        arch = SystemArch().arch
        try:
            desktop = get_desktop_name(os.path.basename(os.getenv("DESKTOP_SESSION")))
        except:
            desktop = "Other"

        if desktop == "Other":
            desktop = get_desktop_name2(os.getenv("XDG_CURRENT_DESKTOP"))
            if desktop == "unknown":
                desktop = os.getenv("XDG_CURRENT_DESKTOP")
        self.screen_factor = 0.0
        if desktop == "Gnome Wayland":
            import gi

            gi.require_version("Gdk", "3.0")
            from gi.repository.Gdk import Display

            # pre-3.22, otherwise deprecated
            # factor = Gdk.Screen.get_default().get_monitor_scale_factor(0)
            self.screen_factor = Display.get_default().get_monitor(0).get_scale_factor()

        # Search active network connections
        if self.net_state.reachability() == QNetworkInformation.Reachability.Online:
            confs = self.net_state.availableBackends()
            netconfs = ", ".join([conf for conf in confs])

        self.configuration = [translate(
                    "ConfList", "<b>Congratulations!</b><BR />You are now running {}"
                ).format(release),
            translate("ConfList", "You are using linux kernel: {}").format(
                    kernel
                ),
            translate("ConfList", "Your system architecture is: {}").format(
                    arch
                ),
            translate(
                    "ConfList", "You are now using the Desktop: {}"
                ).format(desktop),
            translate("ConfList", "Your user id is: {}").format(os.getuid()),
        ]
        if self.net_state.reachability() == QNetworkInformation.Reachability.Online:
            self.configuration.append(
              translate("ConfList", "You are connected to a network through {}").format(netconfs)
            )
        else:
            self.configuration.append(
                translate("ConfList", "You have no network connection")
            )

    def factor(self, app):
        """
        Determine screen factor
        Can be specific for Gnome Wayland
        """
        if self.screen_factor == 0:
            screen = app.primaryScreen()
            self.screen_factor = screen.devicePixelRatio()
        return self.screen_factor

class SystemArch():
    def __init__(self):
        
        if os.uname()[4] == ("x86_64", "aarch64"):
            self.arch = "64-bit"
        elif os.uname()[4] in ("i586", "i686", "armv7hl"):
            self.arch = "32-bit"
        else:
            self.arch = os.uname()[4]
