#!/usr/bin/env bash
# Attempt to format the current buffer based on the filetype
source "$HOME/.ad/lib/ad.sh"

requireAd
fname=$(bufRead "$bufid" filename)
addr=$(bufRead "$bufid" addr)
maybext="${fname##*.}"

case $maybext in
  dart) formatted=$(bufRead "$bufid" body | dart format) ;;
  json) formatted=$(bufRead "$bufid" body | jq) ;;
  rs) formatted=$(bufRead "$bufid" body | rustfmt --edition 2021) ;;
  *) adError "no format rules found for '$maybext'" ;;
esac

if [[ -n "$formatted" ]]; then
  echo -n "," | bufWrite "$bufid" xaddr
  echo -n "$formatted" | bufWrite "$bufid" xdot
  echo -n "$addr" | bufWrite "$bufid" addr
  adCtl "viewport-center"
fi
