" Helps with running a shell command and opens it result in another tab. Most
" helpful with GStreamer logs to run filters like rg 'pipeline|udpsink' %.
function! s:ExecuteInShell(command) " {{{
  let command = join(map(split(a:command), 'expand(v:val)'))
  let winnr = bufwinnr('^' . command . '$')
  silent! execute  winnr < 0 ? 'tabedit ' . fnameescape(command) : winnr . 'wincmd w'
  setlocal buftype=nowrite bufhidden=wipe nobuflisted noswapfile nowrap nonumber
  silent! execute 'silent %!'. command
  silent! redraw
  silent! execute 'au BufUnload <buffer> execute bufwinnr(' . bufnr('#') . ') . ''wincmd w'''
  silent! execute 'nnoremap <silent> <buffer> q :q<CR>'
  echo 'Shell command ' . command . ' executed.'
endfunction " }}}
command! -complete=shellcmd -nargs=+ Shell call s:ExecuteInShell(<q-args>)

" Make a visual selection first. This function then opens a scratch buffer
" in a new tab, pastes the visual selection and runs jq on the buffer
" replacing its contents. Helps with analysing portions of pino logs processed
" by pino-pretty.
function! s:JqScratch()
  tabnew
  noswapfile hide enew
  setlocal buftype=nofile
  setlocal bufhidden=hide
  setlocal nobuflisted
  file scratch
  norm p
  silent! execute '%!jq'
  silent! execute 'set ft=json'
  silent! execute 'nnoremap <silent> <buffer> q :bw<CR>'
endfunction
command! JqScratch call s:JqScratch()

function! GetDecimal()
  execute 'normal! viw'
  let hex = expand("<cword>")
  if stridx(hex, "0x") == 0
    let decimal = trim(system("printf '%d\n' " . hex))
  else
    let decimal = trim(system("printf '%d\n' 0x" . hex))
  endif
  echo decimal
  call system('wl-copy ' . string(decimal))
  execute "normal! \e\eb"
endfunction

function! GetHexaDecimal()
  execute 'normal! viw'
  let decimal = expand("<cword>")
  let hex = trim(system("printf '%x\n' " . decimal))
  echo hex
  call system('wl-copy ' . string(hex))
  execute "normal! \e\eb"
endfunction

nnoremap <Leader><Leader>j :JqScratch<CR>
nnoremap <Leader><Leader>s :Shell rg '' %<Left><Left><Left>

nnoremap <LocalLeader>h :call GetDecimal()<CR>
nnoremap <LocalLeader>H :call GetHexaDecimal()<CR>
