from std/osproc import execProcess, ProcessOption, startProcess, waitForExit, close
from std/envvars import existsEnv, getEnv, delEnv, putEnv
from std/os import symlinkExists, getConfigDir, `/`
from std/options import Option, some, get, isNone
from std/strutils import split, endsWith
from std/strformat import fmt
import owlkettle

const
  # Set the directory path where icons are stored
  iconsDir = "/usr/share/tromjaro-theme-switcher/icons"
  # GTK CSS for overriding the default icon size of buttons
  gtkCSS = "button { -gtk-icon-size: 85px; }"
  applicationID = "com.tromjaro.ThemeSwitcher"
  themeColors = ["Grey", "Pink", "Green", "Orange", "Purple", "Yellow", "Teal"]
  themeStyles = ["Light", "Nord", "Dark", "Dark-Nord"]

proc runCommand(command: string, args: openArray[string]): bool =
  ## This will run a command with the given args and return true upon success
  let process = startProcess(command, args=args, options={poParentStreams})
  result = process.waitForExit() == 0
  process.close()

proc setIconTheme(iconName: string) =
  # Change icon theme in XFCE
  discard runCommand("/usr/bin/xfconf-query",
    args=["--channel=xsettings", "--property=/Net/IconThemeName", "--create", "--type=string", "--set", iconName])

proc enableDarkPanels(): bool =
  # Return if dark panels is already enabled
  if execProcess("/usr/bin/xfconf-query",
    args=["--channel=xfce4-panel", "--property=/panels/dark-mode"], options={}) == "true\n":
    return
  # Try to enable it and return true upon success
  result = runCommand("/usr/bin/xfconf-query",
    args=["--channel=xfce4-panel", "--property=/panels/dark-mode", "--create", "--type=bool", "--set=true"])

proc setTheme(themeName: string) =

  var panelNotification: string

  # Set the icon theme and panel color according to the chosen theme
  if themeName.endsWith("-Dark") or themeName.endsWith("-Dark-Nord"):
    setIconTheme("zafiro-dark")
  else:
    setIconTheme("zafiro")
    if enableDarkPanels():
      panelNotification = " with dark panels"

  # Change the main theme to the chosen one
  discard runCommand("/usr/bin/xfconf-query",
    args=["--channel=xsettings", "--property=/Net/ThemeName", "--create", "--type=string", "--set", themeName])

  # Send notification about the theme change
  sendNotification(applicationID, "Theme Switcher", fmt"{themeName} theme{panelNotification} is enabled",
    icon=fmt"{iconsDir}/{themeName}.svg")


var
  oldConfigDir: Option[string]
  configDirChanged: bool

# Prevent loading GTK theme from ~/.config/gtk-4.0 directory when it is a symlink
if symlinkExists(getConfigDir() / "gtk-4.0"):
  if existsEnv("XDG_CONFIG_HOME"):
    oldConfigDir = some(getEnv("XDG_CONFIG_HOME"))
  putEnv("XDG_CONFIG_HOME", "/dev/null")
  configDirChanged = true

# Display the GTK-4 GUI using owlkettle
viewable App:
  highlightButton: array[2, string]
  hooks:
    build:
      # Reset the user's XDG_CONFIG_HOME variable back to what it was before
      if configDirChanged == true:
        if oldConfigDir.isNone():
          delEnv("XDG_CONFIG_HOME")
        else:
          putEnv("XDG_CONFIG_HOME", get(oldConfigDir))

      let currentTheme: string = execProcess("/usr/bin/xfconf-query",
        args=["--channel=xsettings", "--property=/Net/ThemeName"],
        options={})[0 .. ^2]

      let currentThemeSplit: seq[string] = currentTheme.split('-', 2)

      if currentThemeSplit.len() < 3 or currentThemeSplit[0] != "Colloid":
        return

      let currentThemeColor = currentThemeSplit[1]
      let currentThemeStyle = currentThemeSplit[2]

      # Highlight current theme button
      state.highlightButton = [currentThemeColor, currentThemeStyle]

method view(app: AppState): Widget =
  result = gui:
    Window:
      title = "TROMjaro Theme Switcher"
      # Shrink window to the smallest size
      defaultSize = (0, 0)
      iconName = "tromjaro-theme-switcher"
      # Vertical box
      Box(orient = OrientY, margin = 7, spacing = 5):
        Label:
          text="A Theme Switcher for TROMjaro's default theme-set (Colloid) and icon-set (Zafiro)."
        Label {.vAlign: AlignStart.}:
          useMarkup = true
          text="<span size='small'>NOTE: Some apps need to be reopened for the theme to be applied.</span>"
        for themeStyle in themeStyles:
          # Horizontal box
          Box(orient = OrientX, spacing = 5):
            for themeColor in themeColors:
              Button {.vAlign: AlignCenter, hAlign: AlignCenter.}:
                icon = fmt"Colloid-{themeColor}-{themeStyle}"
                # Teal-Dark-Nord theme will have "(default)" added to its tooltip
                tooltip = if (themeColor, themeStyle) == ("Teal", "Dark-Nord"):
                    fmt"{themeColor}-{themeStyle} (default)"
                  else:
                    fmt"{themeColor}-{themeStyle}"
                style = if [themeColor, themeStyle] == app.highlightButton:
                    ButtonSuggested
                  else:
                    ButtonFlat
                proc clicked() =
                  setTheme(fmt"Colloid-{themeColor}-{themeStyle}")
                  # Highlight this button
                  app.highlightButton = [themeColor, themeStyle]

brew(applicationID, gui(App()), icons=[iconsDir], stylesheets=[newStylesheet(gtkCSS)])
