# shellcheck disable=SC1090,SC1091,SC2312
# ~ works ok here
# . ~/dev/dotfiles/scripts/__reusable_variables.sh


alias ddg='ddg_function'
# need to alias this because regular ddg doesnt open firefox any more
ddg_function() {
  web_search duckduckgo "$@"
  wmctrl -a "$(wmctrl -l | grep -i 'firefox' | awk '{print $NF}' | head -n 1)"
}


watch() {
  if [ $# -eq 0 ]; then
    command viddy
  else
    # shellcheck disable=SC3050
    command viddy --shell zsh "source ~/.zsh_aliases; eval $(printf '%q ' "$@")"
  fi
}


gco() {
  git branch | fzf | xargs -I {} git checkout {} 
}


# alias ghcurrentbranch='ghcurrentbranch_function'

# # need to alias this because regular ddg doesn't open firefox any more
# ghcurrentbranch_function() {
#   if git rev-parse --is-inside-work-tree > /dev/null 2>&1; then
#     gh repo view --branch "$(git rev-parse --abbrev-ref HEAD)" --web
#     wmctrl -a "$(wmctrl -l | grep -i 'firefox' | awk '{print $NF}' | head -n 1)"
#   else
#     echo "Not a git repository."
#   fi
# }

cds() {
  session=$(tmux display-message -p '#{session_path}')
  cd "${session}" || return
}

short() {
  if [ -z "$1" ]; then
    echo "Folder name is required."
    return 1
  else
    take "$1"
  fi
  cp ~/dev/shorts/templates/demo.sh .
  clear
}

cfp() {
    file_path="$1"
    full_path=$(realpath "${file_path}")
    printf '%s' "${full_path}" | xclip -selection clipboard
}

# record() {
#   # run noisetorch to reduce noise
#   noisetorch &
# }

# shellcheck disable=SC2016
pkill() {
  ps aux | 
  fzf --height 40% \
      --layout=reverse \
      --header-lines=1 \
      --prompt="Select process to kill: " \
      --preview 'echo {}' \
      --preview-window up:3:hidden:wrap \
      --bind 'F2:toggle-preview' |
  awk '{print $2}' |
  xargs -r bash -c '
      if ! kill "$1" 2>/dev/null; then
          echo "Regular kill failed. Attempting with sudo..."
          sudo kill "$1" || echo "Failed to kill process $1" >&2
      fi
  ' --
}

# to create and activate a Python virtual environment
mkvenv() {    # Set the environment directory name, default to 'venv' if no name provided
    env_dir=${1:-venv}
    requirements_path="captured-requirements.txt"
    # Check if the environment already exists
        # Create the virtual environment
        echo "Creating new virtual environment '${env_dir}'..."
        python3 -m venv "${env_dir}"
        # Activate the virtual environment
        . "${env_dir}"/bin/activate
        # Optional: Install any default packages
        pip3 install --upgrade pip
        pip3 install wheel
        if [ -f "${requirements_path}" ]; then
            echo "Installing packages from '${requirements_path}'..."
            pip3 install -r "${requirements_path}"
        fi
        echo "Virtual environment '${env_dir}' created and activated!"
  }

rmvenv() {
  # Check if the environment is active
  requirements_path="captured-requirements.txt"
  # shellcheck disable=SC2154
  if [ "${VIRTUAL_ENV}" != "" ]; then
    if [ ! -f "requirements.txt" ]; then
      pip3 freeze > "${requirements_path}"
    fi
    # Deactivate the environment
    deactivate
    echo "Virtual environment deactivated and all installed packages captured"
  else
    echo "No virtual environment is active."
  fi
}

saver() {
  if [ -z "$1" ]; then
    echo "Provide hidden text to save"
    return 1
  fi
  tmatrix --mode=default --fall-speed=0,1 --title="$1" --color=green --background=black 
}

crypt() {
  ENCRYPTED_DIR="${HOME}/dev/encrypted"
  # Check if the current directory is the mount point or a subdirectory of it
  # shellcheck disable=SC2154
  if pwd | grep -q "^${MOUNT_POINT}"; then
    echo "You are currently in the encrypted directory. Changing to home directory."
    cd ~/dev || return 1
  fi
  if findmnt -M "${ENCRYPTED_DIR}" > /dev/null; then
    fusermount -u "${ENCRYPTED_DIR}" && echo "Encrypted directory unmounted successfully." || echo "Failed to unmount encrypted directory."
    echo "Logged out from bitwarden."
  else
    echo "Encrypted directory is not mounted."
  fi
}

uncrypt() {
  if [ -n "$(\ls -A ~/dev/encrypted)" ]; then
    echo "Directory is not empty, assuming already uncrypted, switching to directory."
  elif encfs ~/.encrypted ~/dev/encrypted; then
    echo "Encrypted directory mounted successfully."
  else
    echo "Failed to mount encrypted directory."
    return
  fi
  
  cd ~/dev/encrypted && ls
}

# Define custom copy function
copy_and_create_folders() {
    echo "Debug: copy_and_create_folders called"  # Debug line
    last_arg="${!#}"  # This will get the last argument
    echo "Debug: last_arg=${last_arg}"
    echo "Debug: dirname of last_arg=$(dirname "${last_arg}")"
    if [ ! -d "${last_arg}" ] && [ ! -d "$(dirname "${last_arg}")" ]; then
      echo "Debug: Inside if condition"
        target_dir="$(dirname "${@[-1]}")"
        mkdir -p "${target_dir}"
        echo "Created directory structure: ${target_dir}"
    fi
    
    # Now use the regular cp command
    command cp "$@"
}

apply_pattern() {
    awk "NR == 1 || /$1/"
}

play_song() {
    # Check if a song name is provided
    if [ -z "$1" ]; then
        echo "Provide song name"
        return 1
    fi

    # Determine the song URL based on the input
    case $1 in
        "bek")
            song_url="https://www.youtube.com/watch?v=K3SLQiTC4tM"
            ;;
        "lustmord")
            song_url="https://youtu.be/nj_DqmRac78"
            ;;
        *)
            echo "Song not found"
            return 1
            ;;
    esac

    echo "Playing ${song_url}"

    # Start mpv in the background without video and redirect its output
    echo "Starting mpv..."
    mpv --loop-file --ytdl --no-video "${song_url}" >/dev/null 2>&1 &

    echo "mpv process ID: $!"
}

# xev wrapper for ascii keycodes
char2hex() {
  xev | awk -F'[ )]+' '/^KeyPress/ { a[NR+2] } NR in a { printf "%-3s %s\n", $5, $8 }'
}


# Creates a folder named with the current or prefixed date, using the format "prefix-YYYY-MM-DD" if a prefix is provided.
mkdd ()
{
 mkdir -p ${1:+$1${prefix_separator}}"$(date +%F)"; }


# common to search for a string in files using rga and fzf, and opens the file with nvim.
_fif_common() {
  ignore_case_flag="$1"
  shift
  files
  preview_cmd=$(printf "rga %s --pretty --context 10 '%s' {}" "${ignore_case_flag}" "$*")
  rga_output=$(rga --max-count=1 "${ignore_case_flag}" --files-with-matches --no-messages "$*")
  # PROJECT: project
  # This is used to copy file names so that they can be used a project documentaiton
  echo "${rga_output}" | xsel --clipboard --input
  IFS=$'\n' files=($(echo "${rga_output}" | fzf-tmux +m --preview="${preview_cmd}" --multi --select-1 --exit-0)) || return 1
  if [ ${#files[@]} -eq 0 ]; then
    echo "No files selected."
    return 0
  fi
  # typeset -a temp_files
  for i in {1..${#files[@]}}; do
    if [ -n "${files[i]}" ]; then
      temp_files[i]=$(realpath "${files[i]}")
    fi
  done
  files=("${temp_files[@]}")
  nvim_cmd=""
  case "${#files[@]}" in
    2)
      nvim -O "${files[1]}" "${files[2]}"
      ;;
    3)
      nvim_cmd="nvim -O \"${files[1]}\" -c 'wincmd j' -c \"vsplit ${files[2]}\" -c \"split ${files[3]}\""
      ;;
    4)
      nvim_cmd="nvim -O \"${files[1]}\" -c \"vsplit ${files[2]}\" -c \"split ${files[3]}\" -c 'wincmd h' -c \"split ${files[4]}\""
      ;;
    *)
      nvim_cmd="nvim \"${files[@]}\""
      ;;
  esac
  eval "$nvim_cmd"
}
# Wrapper for case-sensitive search
fifs() {
    _fif_common "" "$@"
}
# Wrapper for case-insensitive search
fif() {
    _fif_common "--ignore-case" "$@"
}

# dedicated to list all files associated with a given project tag
list_project_files() {
    projects_file="${HOME}/projects.txt"
    current_dir="$(pwd)"
    # check if projects file exists
    if [ ! -f "${projects_file}" ]; then
        echo "Error: ${projects_file} not found"
        return 1
    fi
    # use fzf to select project from projects.txt
    # shellcheck disable=SC2002,SC20189
    selected_project=$(cat "${projects_file}" | fzf --height=40% --border=rounded \
        --prompt="Select project > " \
        --preview="rga --max-count=1 'PROJECT: {}' ." \
        --preview-window="right:50%:wrap")
    # exit if no project selected
    if [ -z "${selected_project}" ]; then
        return 0
    fi
    # search for project files
    project_tag="PROJECT: ${selected_project}"
    # use rga to find files containing the project tag in current directory and subdirectories
    rga_output=$(rga --max-count=1 --files-with-matches --no-messages "${project_tag}" .)
    # check if any files were found
    if [ -z "${rga_output}" ]; then
        echo "No files found for project ${selected_project} in ${current_dir}"
        return 0
    fi
    # print each file path
    echo "${rga_output}"
}
# Wrapper for project tags search with optional listing
# PROJECT: project
fifp() {
    mode="$1"  # Check for the '-l' flag
    if [ "${mode}" = "-l" ]; then
        shift  # Remove the first argument (the '-l' flag)
        list_project_files "$*"
    else
        _fif_common "" "PROJECT: $*"
    fi
}

# uploads content to clbin and copies URL to clipboard, opens in browser
share ()
{
    image_path="/tmp/screenshot.png"

    # Save the clipboard content to a file
    # Adjust this command based on your system and the clipboard content
    xclip -selection clipboard -t image/png -o > "$image_path"

    # Upload the image file and parse the JSON response to get the link
    response=$(curl -sF "file=@$image_path" https://file.io)
    url=$(echo "${response}" | jq -r '.link')

    # check if the URL is valid
    # shellcheck disable=SC2249
    case "$url" in
      "https://file.io/"*)
    # if [ "$url" != "https://file.io/"* ]; then
        echo "Error: Invalid URL received"
        return 1
    # fi
    esac

    # handle the URL (copy to clipboard, open in browser, etc.)
    echo "${url}" | tee >(xsel -ib)
    nohup xdg-open "${url}" >/dev/null 2>&1 &
}

# Copy file name to clipboard
cname() {
  stat -t "$1" | cut -d ' ' -f1 | xargs echo -n | xsel -ib
}

# Copy the current working directory path to the clipboard
cpa() {
    if command -v xclip > /dev/null; then
        printf "%s" "${PWD}" | xclip -selection clipboard
        printf "%s\n" "Current working directory ('$(basename "${PWD}")') path copied to clipboard."
    else
        printf "%s\n" "Error: 'xclip' command not found. Please install 'xclip' to use this function."
    fi
}

# Change the directory to the path stored in the clipboard
dpa() {
    if command -v xclip > /dev/null; then
        target_dir
        target_dir="$(xclip -o -sel clipboard)"
        if [ -d "${target_dir}" ]; then
            cd "${target_dir}" && printf "%s\n" "Changed directory to: ${target_dir}"
        else
            printf "%s\n" "Error: Invalid directory path or directory does not exist."
        fi
    else
        printf "%s\n" "Error: 'xclip' command not found. Please install 'xclip' to use this function."
    fi
}

# Add all changes to git, commit with given message, and push
gac() {
  git add .
  git commit -m "$1"
  git push
}

# Add all changes to git, commit with given message and signed-off-by line, and push
gacs() {
  git add .
  git commit -m "$1" -s
  git push
}

# find a repo for authenticated user with gh CLI and cd into it, clone and cd if not found on disk
repo() {
  repo=$(fd . "${HOME}"/dev --type=directory --max-depth=1 --color always| awk -F "/" '{print $5}' | fzf --ansi --preview 'onefetch /home/decoder/dev/{1}' --preview-window up)
  export repo
  if [ -z "${repo}" ]; then
    echo "Repository not found"
    else
    echo "Repository found locally, entering"
    cd "${HOME}"/dev/"${repo}" || return
    if [ -d .git ]; then
      echo "Fetching origin"
      git fetch origin
      onefetch
    fi
  create_tmux_session "${HOME}/dev/${repo}"
  fi
}

create_tmux_session() {
    RESULT="$1"
    zoxide add "$RESULT" >/dev/null 2>&1
    FOLDER=$(basename "$RESULT")
    SESSION_NAME=$(echo "$FOLDER" | tr ' .:' '_')
    if [ -d "$RESULT/.git" ]; then
      SESSION_NAME+="_$(git -C "$RESULT" symbolic-ref --short HEAD 2>/dev/null)"
    fi
    if ! tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
      tmux new-session -d -s "$SESSION_NAME" -c "$RESULT"
    fi
    if [ -z "$TMUX" ]; then
      tmux attach -t "$SESSION_NAME"
    else
      tmux switch-client -t "$SESSION_NAME"
    fi
}

# switch primary monitor between HDMI and DVI-D-0
mon()
{
  active_mon=$(xrandr | grep primary)

  if [[ "$active_mon" =~ "HDMI" ]]; then
    xrandr --output DVI-D-0 --primary
  else
    xrandr --output HDMI-0 --primary
  fi
}

sout () {
    echo "Usage: sout toggles between"
    echo " - hdmi: plays sound via main monitor or"
    echo " - head: plays sound via main headset"
    echo

    current_output=$(wpctl status | grep -A 3 'Sinks:' | grep -e "*" | grep -oP '\d+(?=\.)' | head -n 1)
    hdmi_output=$(wpctl status | grep 'GP106 High Definition Audio Controller Digital Stereo' | grep -oP '\d+(?=\.)' | head -n 1)
    headset_output=$(wpctl status | grep 'PRO X Wireless Gaming Headset Analog Stereo' | grep -oP '\d+(?=\.)' | head -n 1)

    echo "Debug: current_output=$current_output"
    echo "Debug: hdmi_output=$hdmi_output"
    echo "Debug: headset_output=$headset_output"

    if [ -z "${current_output}" ] || [ -z "${hdmi_output}" ] || [ -z "${headset_output}" ]
    then
        echo "Error: Unable to determine audio outputs"
        return 1
    fi

    if [ "${current_output}" = "${hdmi_output}" ]; then
        new_output=$headset_output
        echo "Debug: Switching to headset"
    else
        new_output=$hdmi_output
        echo "Debug: Switching to HDMI"
    fi

    echo "Debug: new_output=$new_output"

    wpctl set-default "$new_output"

    if [ "${new_output}" = "${hdmi_output}" ]; then
        mic_id=$(wpctl status | grep "Microphone Mono" | grep -oP '\d+(?=\.)' | head -n 1)
        if [ -n "${mic_id}" ]; then
            wpctl set-mute "$mic_id" 1
        else
            echo "Warning: Unable to find microphone ID"
        fi
        wpctl set-volume @DEFAULT_AUDIO_SINK@ 50%
        echo "Sound output set to hdmi=monitor, mic muted (if found)"
        echo "Volume 50%"
    else
        wpctl set-volume @DEFAULT_AUDIO_SINK@ 75%
        echo "Sound output set to head=headset"
        echo "Volume 75%"
    fi
}
