#!/usr/bin/env -S emacs -x
;; -*- mode: emacs-lisp; lexical-binding: t -*-
(require 'cl-lib)
(require 'server)
(require 'dbus)

(defun cmdline-for-pid (pid)
  "Return the command line arguments passed to PID.
PID can be a string or a number."
  (butlast (string-split
            (with-temp-buffer
              (insert-file-contents-literally
               (format "/proc/%s/cmdline" pid))
              (buffer-substring-no-properties (point-min)
                                              (point-max)))
            "\0")))
(defun current-eww-config-dir ()
  "Return the configuration directory for a currently running eww process."
  ;; This probably only works on Linux
  (catch 'found
    (dolist (subdir (directory-files "/proc"))
      (when (string-match-p (rx bos (+ num) eos) subdir)
        (ignore-error permission-denied
          (let* ((attrs (file-attributes (format "/proc/%s/exe" subdir)))
                 (type (file-attribute-type attrs)))
            (when (and (stringp type)
                       (string-match-p (rx (or bos "/") "eww") type))
              (cl-maplist (lambda (tail)
                            (when (equal (car tail) "-c")
                              (throw 'found (cl-second tail))))
                          (cmdline-for-pid subdir)))))))))

(defun set-eww-fcitx-state (state)
  "Set the Fcitx state for Eww to STATE."
  (let ((args (list "update" (format "fcitx5-state=%s" state)))
        (cfg-dir (current-eww-config-dir)))
    (when cfg-dir
      (setq args (nconc (list "-c" cfg-dir) args)))
    (apply 'call-process "eww" nil 0 nil args)))

(cl-defun has-focused-window-p (&optional (server "server"))
  "Return non-nil if SERVER has at least one focused window.
SERVER defaults to \"server\"."
  (server-eval-at
   server '(cl-some 'frame-focus-state (frame-list))))

(if (has-focused-window-p)
    (server-eval-at "server" '(my/global-toggle-mozc))
  (dbus-call-method :session "org.fcitx.Fcitx5" "/controller"
                    "org.fcitx.Fcitx.Controller1" "Toggle")
  (let ((state (dbus-call-method :session "org.fcitx.Fcitx5" "/controller"
                                 "org.fcitx.Fcitx.Controller1" "State")))
    (set-eww-fcitx-state state)))

;; Local Variables:
;; flycheck-disabled-checkers: (emacs-lisp-checkdoc)
;; End: