(deflisten media-info :initial '{}' `~/.config/scripts/playerctl-metadata-json.sh`)
(deflisten media-status :initial 'stopped' 'playerctl status --follow')
(defpoll media-playback-info :interval '1s' :initial '0' `playerctl position`)

(defvar statusIcons '{"Playing": "player_play", "Paused": "player_pause"}')

(defvar media-close-time 0)

(defwidget icon-button [icon onclick]
  (button 
    :onclick {onclick}
    :vexpand false

    (image :icon {icon})
  )
)

(defwidget media-label [text ?header ?icon]
  (box
    :visible {strlength(text) > 1}
    :space-evenly false
    :spacing 10
    (image :icon {icon})
    (label :text {text} :xalign "0" :class {header ? "header" : ""})
  )
)

(defwidget media-texts [] 
  (box 
    :orientation "vertical"
    :hexpand true
    :valign "center"
    :halign "start"
    :space-evenly false
    (media-label :header true :text {media-info["xesam:title"]} :icon "library-music")
    (media-label :text {media-info["xesam:artist"]} :icon "user-identity")
    (media-label :text {media-info["xesam:album"] ?: ""} :icon "cd")
  )
)

(defwidget media-control []
  (box 
    :visible {EWW_TIME < media-close-time}
    :class "widget"
    :width 512
    :space-evenly false
    :orientation "v"

    (box
      :class "data-display"
      :valign "center"
      :halign "start"
      :space-evenly false
      :spacing 20
      (box
        :width {512 - 128}

        :space-evenly false
        :orientation "vertical"
        :spacing 10
        (media-texts)
        (box :vexpand true)
        (box
          :hexpand true
          :vexpand false
          :spacing 10
          (icon-button
            :icon "player_rew"
            :onclick "~/.config/scripts/media.sh previous"
            )

          (icon-button
            :icon {statusIcons[media-status] ?: "player_stop"}
            :onclick "~/.config/scripts/media.sh play-pause"
            )
          (icon-button
            :icon "player_fwd"
            :onclick "~/.config/scripts/media.sh next"
            )
          )
      )

      (image
        :path {media-info["mpris:artUrl"]}
        :image-width 128
      )
    )
    (progress
      :height 1
      :value {jq(media-playback-info, "tonumber(.)") / (jq(media-info["mpris:length"] ?: 1000, "tonumber(.)") / 1000000) * 100}
      )
  )
)
(defwindow media
  :monitor 1
  :geometry (geometry 
  :x "10px"
  :y "50px"
  :width "0px"
  :height "10%"
  :anchor "top right")
  :stacking "fg"
  (media-control)
  )
