from std/osproc import ProcessOption, startProcess, waitForExit, close
from std/options import Option, some, get, isNone
from std/strutils import splitLines
from std/strformat import fmt
import owlkettle, std/os

const
  picturesDir = "/usr/share/tromjaro-welcome-app/pictures"
  desktopFile = "tromjaro-welcome-app.desktop"
  desktopFilePath = "/usr/share/applications" / desktopFile
  applicationID = "com.tromjaro.WelcomeApp"

let
  autostartSymlinkPath = getConfigDir() / "autostart" / desktopFile

const pages = [
  (
    title: "Welcome to TROMjaro",
    description: """
This operating system is trade-free.
This means that you do not have to trade anything to us in order to use it.
Not your data, not your attention, currency or anything else.
There are no free trials here, no ads, and no trackers.
    """,
    image: "",
    buttonText: "TAKE A MINUTE TO CUSTOMIZE YOUR DESKTOP EXPERIENCE",
    buttonCommand: @[]
  ),
  (
    title: "Choose a Layout",
    description: "Make it morph into any configuration you like!",
    image: "layout-switcher-thumbnail.png",
    buttonText: "OPEN THE LAYOUT SWITCHER",
    buttonCommand: @["/usr/bin/tromjaro-layout-switcher"]
  ),
  (
    title: "Choose a Theme",
    description: "Choose between the many variations of themes that sync across different types of applications.",
    image: "theme-switcher-thumbnail.png",
    buttonText: "OPEN THE THEME SWITCHER",
    buttonCommand: @["/usr/bin/tromjaro-theme-switcher"]
  ),
  (
    title: "Choose a Background",
    description: "Pick a cool background to go along with your theme!",
    image: "wallpapers-thumbnail.png",
    buttonText: "CHANGE THE WALLPAPER",
    buttonCommand: @["/usr/bin/xfdesktop-settings"]
  ),
  (
    title: "Setup the Internet Content Blocker",
    description: "Setup your Operating System to block pesky ads and trackers, system-wide.",
    image: "tblock-thumbnail.png",
    buttonText: "SETUP INTERNET CONTENT BLOCKER",
    buttonCommand: @["/usr/bin/tblockg"]
  ),
  (
    title: "Settings Manager",
    description: "If you want to do more tweaks, you will find all of the settings in one single place.",
    image: "settings-manager-thumbnail.png",
    buttonText: "OPEN SETTINGS MANAGER",
    buttonCommand: @["/usr/bin/xfce4-settings-manager"]
  ),
  (
    title: "Support Us",
    description: "TROMjaro is one of the many trade-free projects that we are doing. Please support us if you can. Thank you!",
    image: "trom-projects-thumbnail.png",
    buttonText: "DONATE",
    buttonCommand: @["/usr/bin/xdg-open", "https://www.tromsite.com/donate/"]
  )
]

var pageNumber: int = 0

proc runBackgroundCommand(commandLine: seq[string]) =
  let process = startProcess("/usr/bin/setsid", args= @["-f"] & commandLine, options={poParentStreams})
  discard process.waitForExit()
  process.close()

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

viewable App:
  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))

method view(app: AppState): Widget =
  result = gui:
    Window:
      title = "TROMjaro Welcome"
      defaultSize = (900, 600)
      Box(orient = OrientY, margin = 20, spacing = 15):
        Label:
          useMarkup = true
          text = fmt"<span size='x-large' weight='bold'>{pages[pageNumber].title}</span>"
        for line in splitLines(pages[pageNumber].description):
          Label {.expand: false.}:
            useMarkup = true
            text = fmt"<span size='large'>{line}</span>"
        if pages[pageNumber].image != "":
          Box(margin = 20):
            Picture:
              Pixbuf = loadPixbuf(picturesDir / pages[pageNumber].image)
        Button {.vAlign: AlignCenter, hAlign: AlignCenter.}:
          text = pages[pageNumber].buttonText
          style = ButtonSuggested
          proc clicked() =
            let command: seq[string] = pages[pageNumber].buttonCommand
            if command.len() == 0:
              inc pageNumber
              return
            runBackgroundCommand(command)
        if pageNumber > 0:
          Box(orient = OrientX):
            Button {.hAlign: AlignStart, vAlign: AlignCenter.}:
              text = "Previous"
              proc clicked() =
                dec pageNumber
            if pageNumber == pages.high():
              Button {.hAlign: AlignEnd, vAlign: AlignCenter.}:
                text = "Finish"
                proc clicked() =
                  app.closeWindow()
            else:
              Button {.hAlign: AlignEnd, vAlign: AlignCenter.}:
                text = "Next"
                proc clicked() =
                  inc pageNumber
        Box(orient = OrientX, spacing = 12):
          Label {.hAlign: AlignEnd.}:
            text = "Open this Welcome Screen on every boot"
          Switch {.vAlign: AlignCenter, hAlign: AlignStart.}:
            state = if symlinkExists(autostartSymlinkPath): true else: false
            proc changed(state: bool) =
              if state == true:
                if not symlinkExists(autostartSymlinkPath):
                  try:
                    createSymlink(desktopFilePath, autostartSymlinkPath)
                  except:
                    echo "Failed to create symlink!"
              else:
                if not tryRemoveFile(autostartSymlinkPath):
                  echo "Failed to remove symlink!"

brew(applicationID, gui(App()))