from std/osproc import execProcess, ProcessOption, startProcess, waitForExit, close
from std/os import symlinkExists, getConfigDir, putEnv, `/`
from std/strutils import split, endsWith, strip
from std/algorithm import fill
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: 22mm; }"
  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("com.tromjaro.ThemeSwitcher", "Theme Switcher", fmt"{themeName} theme{panelNotification} is enabled",
    icon=fmt"{iconsDir}/{themeName}.svg")


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

var
  lastClickedButton: array[2, int]

# Display the GTK-4 GUI using owlkettle
viewable App:
  # 2D array storing the style for each button
  buttonStyles: array[themeStyles.len(),array[themeColors.len(), StyleClass]]
  hooks:
    build:
      # Make all buttons flat by default
      for index in 0..state.buttonStyles.high():
        fill(state.buttonStyles[index], ButtonFlat)

      let currentTheme: string = execProcess("/usr/bin/xfconf-query",
        args=["--channel=xsettings", "--property=/Net/ThemeName"],
        options={}).strip(leading=false, trailing=true, chars={'\n'})

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

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

      let currentThemeColorIndex = find(themeColors, currentThemeSplit[1])
      let currentThemeStyleIndex = find(themeStyles, currentThemeSplit[2])

      if -1 in [currentThemeColorIndex, currentThemeStyleIndex]:
        return

      # Highlight current theme button
      state.buttonStyles[currentThemeStyleIndex][currentThemeColorIndex] = ButtonSuggested
      lastClickedButton = [currentThemeStyleIndex, currentThemeColorIndex]

method view(app: AppState): Widget =
  result = gui:
    Window:
      title = "TROMjaro Theme Switcher"
      # Shrink window to the smallest size
      defaultSize = (0, 0)
      # 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)."
        for y, themeStyle in themeStyles:
          # Horizontal box
          Box(orient = OrientX, spacing = 5):
            for x, 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 = app.buttonStyles[y][x]
                proc clicked() =
                  var thisButton = [y, x]
                  setTheme(fmt"Colloid-{themeColor}-{themeStyle}")
                  # Highlight this button
                  app.buttonStyles[y][x] = ButtonSuggested
                  if lastClickedButton != thisButton:
                    # Remove highlight from lastClickedButton
                    app.buttonStyles[lastClickedButton[0]][lastClickedButton[1]] = ButtonFlat
                    lastClickedButton = thisButton

brew("com.tromjaro.ThemeSwitcher", gui(App()), icons=[iconsDir], stylesheets=[newStylesheet(gtkCSS)])