#!/usr/bin/python3

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, GLib, GdkPixbuf

import subprocess
from subprocess import Popen, PIPE

import os
import sys
import glob

SELFDIR=os.path.dirname(os.path.realpath(__file__))+"/"

def cmdexec(cmd1="",cmd2=""):
  global win
  cmd=cmd1
  if cmd2!="": cmd=cmd2
  cmd=cmd.strip()
  if cmd.endswith('&'):
    print(cmd)
    cmd=cmd[:-1]
    print(cmd)
    subprocess.Popen(cmd,shell=True)
    return
  else:
    a=subprocess.getoutput(cmd)
    return a
    


      
      
def wincmd_online(self,button,befehl,back):
  hideme(self)
  if checkonline():
    cmdexec(befehl)
    if back!=True:
      Gtk.main_quit()
  else:
    dialog=Gtk.MessageDialog(transient_for=self,flags=0,message_type=Gtk.MessageType.INFO,buttons=Gtk.ButtonsType.OK,text="Funktion nicht verfügbar")
    dialog.format_secondary_text("Diese Funktion ist nur verfügbar, wenn Sie mit dem Internet verbunden sind.")
    dialog.run()
    dialog.destroy()
  showme(self)


class HelpWindow(Gtk.Window):    
  def singlebutton(self,text,bild,kommando,kommando2,*_):
    btn0 = Gtk.Button(xalign=0)
    btn0.connect("clicked", kommando, kommando2,*_)
    btn0_grid=Gtk.Grid(margin=10,column_spacing=10,row_spacing=10,hexpand=True,column_homogeneous=True,row_homogeneous=False)
    btn0_label=Gtk.Label(label=text,xalign=0.5,justify=2,use_markup=True);
    btn0_img=Gtk.Image()
    btn0_img.set_from_pixbuf(GdkPixbuf.Pixbuf.new_from_file_at_scale(filename=SELFDIR+bild,width=-1, height=60, preserve_aspect_ratio=True))
    btn0_grid.attach(btn0_img, 0, 0, 1, 1)
    btn0_grid.attach(btn0_label, 0, 1, 1, 1)
    btn0.add(btn0_grid)
    return btn0
    
  def __init__(self):
    global SELFDIR
    super().__init__(title="Hilfe- und Servicecenter")
    if os.path.isfile(SELFDIR+"help.png"):
      self.set_icon_from_file(SELFDIR+"help.png")
    self.set_position(Gtk.WindowPosition.CENTER)
    grid = Gtk.Grid(margin=10,column_spacing=10,row_spacing=10,hexpand=True,column_homogeneous=True,row_homogeneous=False)
    #grid.override_background_color(Gtk.StateType.NORMAL, Gdk.RGBA(.5,.5,.5,.5))
    symbolsize=60


    
    # Kurzeinweisung
    btn0=self.singlebutton("<b>Kurz-Einführung</b>\n", "kurzeinweisung.svg", self.wincmd, SELFDIR+"/Einweisung/bildergalerie.py &")
    grid.attach(btn0, 0, 1, 1, 1)
    if not os.path.isfile("/opt/XLinux/Hilfe/Einweisung/bildergalerie.py"):
      btn0.set_sensitive(False)

    #WLAN-Verbinden
    btn1=self.singlebutton("<b>WLAN</b>\nverbinden", "wifi.svg", self.wincmd, "exo-open '/opt/XLinux/Hilfe/WLAN verbinden.pdf' &")
    grid.attach(btn1, 1, 1, 1, 1)

    # Handbuch
    btn4=self.singlebutton("<b>Handbuch</b>\nPDF", "handbuch.svg", self.wincmd, "exo-open /opt/XLinux/Hilfe/Handbuch_*.pdf &")
    grid.attach(btn4, 2, 1, 1, 1)
    if len(glob.glob("/opt/XLinux/Hilfe/Handbuch_*.pdf"))==0:
      btn4.set_sensitive(False)

    # Hilfe & Anleitungen (Online)
    btn2=self.singlebutton("<b>Support-Webseite</b>\nAnleitungen, Videos &amp; mehr", "onlinehilfe.svg", self.wincmd_online, "exo-open https://support.mastro-it.de/service?uuid="+cmdexec("xlinux-systemid")+" ",False)
    grid.attach(btn2, 3, 1, 1, 1)
   

    # Fernwartung   
    btn3=self.singlebutton("<b>Fernwartung</b>\nkostenpflichtige Hilfe", "fernwartung.svg", self.open_remote_service, "" )
    grid.attach(btn3, 3, 2, 1, 1)
      
    # Softwarecenter
    btn5=self.singlebutton("<b>Software-Center</b>\nAnwendungen &amp; Spiele", "softwarecenter.svg", self.wincmd_online, "/opt/XLinux/softwarecenter/Softwarecenter.py",True )
    grid.attach(btn5, 1, 2, 1, 1)
      
    # Passwort & Benutzerverwaltung
    btn5=self.singlebutton("<b>Benutzerverwaltung</b>\nz.B. Passwort ändern", "benutzerverwaltung.svg",self.open_user_window, "")
    grid.attach(btn5, 0, 2, 1, 1)

    # Passwort & Benutzerverwaltung
    btn5=self.singlebutton("<b>Einstellungen</b>\nUpdates &amp; Tools", "settings.svg",self.open_settings_window, "")
    grid.attach(btn5, 2, 2, 1, 1)
        
    self.add(grid);
    

  def wincmd(self,button,befehl):
    cmdexec(befehl)
    Gtk.main_quit()
    
  def wincmd_online(self,button,befehl,back):
    wincmd_online(self,button,befehl,back)

  def open_remote_service(self,button,*_):
    if checkonline():
      self.hide()
      win=RemoteSupportWindow()
      win.connect("destroy", win.open_main)
      win.show_all()
    else:
      dialog=Gtk.MessageDialog(transient_for=self,flags=0,message_type=Gtk.MessageType.INFO,buttons=Gtk.ButtonsType.OK,text="Fernwartung nicht verfügbar.")
      dialog.format_secondary_text("Stellen Sie bitte die Internetverbindung her. \n \nFalls Sie weitere Hilfe benötigen, kontaktieren Sie uns bitte telefonisch.")
      dialog.run()
      dialog.destroy()
      self.show()

  def open_settings_window(self,button,*_):
    self.hide()
    win=SettingsWindow()
    win.connect("destroy", win.open_main)
    win.show_all()

  def open_user_window(self,button,*_):
    self.hide()
    win=UserWindow()
    win.connect("destroy", win.open_main)
    win.show_all()
      

class SettingsWindow(Gtk.Window):    
  def __init__(self):
    global SELFDIR,ONLINE, OSVERSION
    super().__init__(title="Tools & Einstellungen")
    if os.path.isfile(SELFDIR+"help.png"):
      self.set_icon_from_file(SELFDIR+"help.png")
    self.set_position(Gtk.WindowPosition.CENTER)
    
    hline=0
    update_grid = Gtk.Grid(margin=2,column_spacing=10,row_spacing=5)

    label = Gtk.Label(label="Sicherheitsaktualisierungen suchen und installieren",xalign=0)
    button1 = Gtk.Button(label="Softwareupdate",xalign=0)
    button1.connect("clicked", self.start_software_update, "")
    update_grid.attach(button1, 0, hline, 1, 1)        
    update_grid.attach(label, 1, hline, 4, 1)
    hline=hline+1

    sep=Gtk.Separator(orientation=0); update_grid.attach(sep, 0, hline, 5, 1); hline=hline+1
        
    label = Gtk.Label(label="Datensicherung auf USB-Festplatte einrichten.",xalign=0)
    button1 = Gtk.Button(label="Datensicherung",xalign=0)
    button1.connect("clicked", self.wincmd2, "/opt/XLinux/usbbackup/usbbackup.sh")
    update_grid.attach(button1, 0, hline, 1, 1)        
    update_grid.attach(label, 1, hline, 4, 1)
    hline=hline+1
    
    sep=Gtk.Separator(orientation=0); update_grid.attach(sep, 0, hline, 5, 1); hline=hline+1
    
    label = Gtk.Label(label="Zeitsteuerung zum Abschalten des Bildschirms\nund Computers bei Inaktivität.",xalign=0)
    button1 = Gtk.Button(label="Energieprofil",xalign=0)
    button1.connect("clicked", self.wincmd2, "/usr/bin/xlinux-power-profiles")
    update_grid.attach(button1, 0, hline, 1, 1)
    update_grid.attach(label, 1, hline, 4, 1)
    hline=hline+1
    
    sep=Gtk.Separator(orientation=0); update_grid.attach(sep, 0, hline, 5, 1); hline=hline+1

    label = Gtk.Label(label="Programm zur Einrichtung von HP-Druckern.",xalign=0)
    button1 = Gtk.Button(label="HP-Drucker-Einrichtung",xalign=0)
    button1.connect("clicked", self.wincmd2, "hp-setup")
    update_grid.attach(button1, 0, hline, 1, 1)        
    update_grid.attach(label, 1, hline, 4, 1)
    hline=hline+1
    
    sep=Gtk.Separator(orientation=0); update_grid.attach(sep, 0, hline, 5, 1); hline=hline+1
        
    label = Gtk.Label(label="Setzt das Hindergrundbild und die Energieeinstellungen\nauf die Standard-Werte zurück.",xalign=0)
    button1 = Gtk.Button(label="Desktop-Reset",xalign=0)
    button1.connect("clicked", self.wincmd2, "bash /opt/XLinux/user-autostarts/xfconf-desktop-reset.sh")
    update_grid.attach(button1, 0, hline, 1, 1)
    update_grid.attach(label, 1, hline, 4, 1)
    hline=hline+1
    
    sep=Gtk.Separator(orientation=0); update_grid.attach(sep, 0, hline, 5, 1); hline=hline+1
    
    label = Gtk.Label(label="Stellt die Standard-Einstellung der Taskleiste (Panel unten) wieder her.",xalign=0)
    button1 = Gtk.Button(label="Taskleisten-Reset",xalign=0)
    button1.connect("clicked", self.wincmd2, "bash /opt/XLinux/user-autostarts/xfconf-panel-reset.sh")
    update_grid.attach(button1, 0, hline, 1, 1)
    update_grid.attach(label, 1, hline, 4, 1)
    hline=hline+1


    sw = Gtk.ScrolledWindow(min_content_height=300)
    sw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.ALWAYS)
    sw.add(update_grid)

    grid = Gtk.Grid(margin=2,column_spacing=0,row_spacing=2,hexpand=True,column_homogeneous=True,row_homogeneous=False)
    btn3 = Gtk.Button(label='Zurück zum Hauptmenü',xalign=0.5)
    btn3.connect("clicked", self.open_main)
    grid.attach(sw, 0, 0, 4, 1)
    grid.attach(btn3, 0, 1, 2, 1)
    self.add(grid);


  def wincmd2(self,button,befehl):
    hideme(self)
    cmdexec(befehl)
    showme(self)

  def open_main(self,button):
    global win
    win.show_all()
    self.destroy()
    
  def wincmd_online(self,button,befehl,back):
    wincmd_online(self,button,befehl,back)

  def start_software_update(self,*_):
    hideme(self)
    if checkonline():
      cmdexec("xlinux-update --install --force --allyes --showdesktopmessages &")
      dialog=Gtk.MessageDialog(transient_for=self,flags=0,message_type=Gtk.MessageType.INFO,buttons=Gtk.ButtonsType.OK,text="Updatesuche gestartet")
      dialog.format_secondary_text("Die Suche nach Softwareupdates wurde gestartet.")
      dialog.run()
      dialog.destroy()
      Gtk.main_quit()
    else:
      dialog=Gtk.MessageDialog(transient_for=self,flags=0,message_type=Gtk.MessageType.INFO,buttons=Gtk.ButtonsType.OK,text="Funktion nicht verfügbar")
      dialog.format_secondary_text("Diese Funktion ist nur verfügbar, wenn Sie mit dem Internet verbunden sind.")
      dialog.run()
      dialog.destroy()
    showme(self)


class RemoteSupportWindow(Gtk.Window):    
  def __init__(self):
    global SELFDIR,ONLINE
    super().__init__(title="Fernwartung")
    if os.path.isfile(SELFDIR+"help.png"):
      self.set_icon_from_file(SELFDIR+"help.png")
    self.set_position(Gtk.WindowPosition.CENTER)
    grid = Gtk.Grid(margin=10,column_spacing=20,row_spacing=20,hexpand=True,column_homogeneous=True,row_homogeneous=False)

    label=Gtk.Label(xalign=0)
    label.set_markup("<b>Telefonische Hilfe / Fernwartung</b>\nWenn Sie individuelle Fragen haben, können wir Ihnen persönlich helfen.\nDiese Dienstleistung wird Ihnen nach Zeitaufwand in Rechnung gestellt.\nMehr Informationen über unsere Webseite: <a href='https://www.mastro-it.de'>www.mastro-it.de</a>\n\n<b>Die nächsten Schritte:</b>")
    grid.attach(label, 0, 0, 3, 1)
    btn3_img=Gtk.Image()
    btn3_img.set_from_pixbuf(GdkPixbuf.Pixbuf.new_from_file_at_scale(filename=SELFDIR+"fernwartung.svg",width=100, height=100, preserve_aspect_ratio=True))
    grid.attach(btn3_img, 3, 0, 1, 1)
    
    label_schritt1=Gtk.Label(xalign=0)
    label_schritt1.set_markup("<b>1.</b> Termin für telefonische Unterstützung buchen: <a href='https://www.mastro-it.de/rueckruf'>Termin buchen</a>")
    grid.attach(label_schritt1, 0, 1, 4, 1)

    label_schritt2=Gtk.Label(xalign=0)
    label_schritt2.set_markup("<b>2.</b> Zum Termin müssen Sie telefonisch erreichbar sein und der Computer muss mit dem Internet verbunden sein.")
    grid.attach(label_schritt2, 0, 2, 4, 1)

    label_schritt3=Gtk.Label(xalign=0)
    label_schritt3.set_markup("<b>3.</b> Wir rufen Sie an und werden Sie bei Bedarf auffordern, den 'Verbindung herstellen'-Button zu drücken.")
    grid.attach(label_schritt3, 0, 3, 4, 1)

    btn3 = Gtk.Button(label='Verbindung herstellen',xalign=0.5)
    btn3.connect("clicked", self.wincmd, "/opt/XLinux-Fernwartung/2022_fernwartung.sh &")
    grid.attach(btn3, 3, 4, 1, 1)

    btn3 = Gtk.Button(label='Zurück zum Hauptmenü',xalign=0.5)
    btn3.connect("clicked", self.open_main)
    grid.attach(btn3, 0, 4, 1, 1)
    
    self.add(grid);

  def wincmd(self,button,befehl):
    cmdexec(befehl)
    Gtk.main_quit()

  def open_main(self,button):
    global win
    win.show_all()
    self.destroy()



class UserWindow(Gtk.Window):    
  def singlebutton2(self,text,bild,kommando,kommando2):
    btn0 = Gtk.Button(xalign=0)
    btn0.connect("clicked", kommando, kommando2)
    btn0_grid=Gtk.Grid(margin=10,column_spacing=10,row_spacing=10,hexpand=True,column_homogeneous=False,row_homogeneous=False)
    btn0_label=Gtk.Label(label=text,xalign=0,justify=0,use_markup=True,yalign=0);
    btn0_img=Gtk.Image()
    btn0_img.set_from_pixbuf(GdkPixbuf.Pixbuf.new_from_file_at_scale(filename=SELFDIR+bild,width=-1, height=60, preserve_aspect_ratio=True))
    btn0_grid.attach(btn0_img, 0, 0, 1, 1)
    btn0_grid.attach(btn0_label, 1, 0, 1, 1)
    btn0.add(btn0_grid)
    return btn0
    
  def __init__(self):
    global SELFDIR
    super().__init__(title="Benutzerverwaltung")
    if os.path.isfile(SELFDIR+"help.png"):
      self.set_icon_from_file(SELFDIR+"help.png")
    self.set_position(Gtk.WindowPosition.CENTER)
    grid = Gtk.Grid(margin=10,column_spacing=10,row_spacing=10,hexpand=True,column_homogeneous=True,row_homogeneous=False)
    symbolsize=60
    u=cmdexec("whoami");
    
    # Eigene Benutzerverwaltung
    btn0=self.singlebutton2("<b>Benutzer "+u+" bearbeiten</b>\n- eigenes Passwort ändern\n- Anzeigename ändern\n- automatische Anmeldung ", "passwort.svg", self.wincmd, "/usr/bin/xlinux-user-pwchange")
    grid.attach(btn0, 0, 0, 2, 1)

    # Benutzer anlegen und löschen
    btn1=self.singlebutton2("<b>Andere Benutzer bearbeiten</b>\n- Benutzer anlegen, verwalten &amp; löschen", "benutzerverwaltung.svg", self.wincmd, "/usr/bin/xlinux-useradmin")
    grid.attach(btn1, 0, 1, 2, 1)

    btn3 = Gtk.Button(label='Zurück zum Hauptmenü',xalign=0.5)
    btn3.connect("clicked", self.open_main)
    grid.attach(btn3, 0, 2, 1, 1)

    self.add(grid);
    
  def wincmd(self,button,befehl):
    hideme(self)
    cmdexec(befehl)
    showme(self)

  def open_main(self,button):
    global win
    win.show_all()
    self.destroy()


    

def hideme(s):
  s.set_visible(False)
  while Gtk.events_pending():
    Gtk.main_iteration()

def showme(s):
  s.set_visible(True)
  while Gtk.events_pending():
    Gtk.main_iteration()

def checkonline():
  ONLINE=False
  if cmdexec("xlinux-checkonline").strip()=="ja":
    ONLINE=True
  return ONLINE

win=HelpWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
