(use-modules (ice-9 match))
(use-modules (ice-9 popen))
(use-modules (ice-9 rdelim))
(use-modules (gri3 wm))
(use-modules (gri3 bindings))
(use-modules (gri3 hooks))

(define mode "default")

(define devel #t)

(display "-- GUILE CONFIGURATION START LOADING --\n")

(define (run-shell-command c)
  (system (string-concatenate
	   (list c " &"))))

;; (include "i3.scm")
(define font "pango:Hack 8")
;; (run-shell-command "./i3bar -b 0")

;; xkb_keysym_from_name(symbol, XKB_KEYSYM_NO_FLAGS)

(define (reload)
  (display "Reloading (with refresh)!\n")
  (load "config.scm")
  (refresh))

(define (urxvt)
  (if devel
      (run-shell-command "urxvt")
      (run-shell-command "urxvtc")))

(define (run-and-read command)
  (let* ((port (open-input-pipe command))
	 (str  (read-line port)))	; from (ice-9 rdelim)
    (close-pipe port)
    str))

;; (define (urxvt) (display "URXVT"))

(define (eval-expr) (run-shell-command (format #f "./i3-msg ~S" (run-and-read "echo '' | dmenu"))))

(define (run-program) (run-shell-command "dmenu_run"))

(define-mode-map "M-SPC" 'program-launcher)

(add-key-binding (kbd "M-m") urxvt)
(add-key-binding (kbd "M-RET") urxvt)
(add-key-binding (kbd "M-SPC") run-program)
(add-key-binding (kbd "M-q") kill-window)
(add-key-binding (kbd "M-r") reload)

(add-key-binding (kbd "M-r") reload)

;; Change layout
(add-key-binding (kbd "M-w") (lambda () (layout "tabbed")))
(add-key-binding (kbd "M-s") (lambda () (layout "stacked")))
(add-key-binding (kbd "M-e") (lambda () (toggle-layout "split")))
;; Split
(add-key-binding (kbd "M-v") (lambda () (split "vertical")))
(add-key-binding (kbd "M-h") (lambda () (split "horizontal")))
;; Add workspaces
(for-each
 (lambda (num)
   (add-key-binding
    (kbd (format #f "M-~s" num))
    (lambda () (change-workspace (number->string num))))
   (add-key-binding
    (kbd (format #f "M-S-~s" num))
    (lambda () (move-to-workspace (number->string num)))))
 '(0 1 2 3 4 5 6 7 8 9))
;; Move windows
(add-key-binding (kbd "M-f") (lambda () (focus-direction "right")))
(add-key-binding (kbd "M-b") (lambda () (focus-direction "left")))
(add-key-binding (kbd "M-p") (lambda () (focus-direction "up")))
(add-key-binding (kbd "M-n") (lambda () (focus-direction "down")))

(when (and (not (defined? 'loaded)) (not devel))
  (run-shell-command "setxkbmap && xmodmap ~/.Xmodmap")
  (run-shell-command "emacs --daemon")
  (run-shell-command "mcron")
  (run-shell-command "urxvtd"))

(define loaded #t)
(run-shell-command "feh --randomize --bg-fill ~/memories/incipit/laptop/wallpapers/")
