#!/bin/zsh

tmux_new_session() {
  if [[ -n $TMUX ]]; then
    tmux switch-client -t "$(TMUX= tmux -S "${TMUX%,*,*}" new-session -dP "$@")"
  else
    echo -n "Nombre de Sesión: "
    read REPLY
    if [[ -n $REPLY ]]; then
      tmux -2 new-session -s "$REPLY"
    else
      tmux -2 new-session
    fi
  fi
}

tmux_sessions() {
  # Select existing session or create session with fuzzy search tool
  # get the IDs
  if ! ID="$(tmux list-sessions 2>/dev/null)"; then
    # tmux returned error, so try cleaning up /tmp
    \rm -rf /tmp/tmux*
  fi
  create_new_session="Crear Sesión"
  if [[ -n "$ID" ]]; then
    ID="${create_new_session}:\n$ID"
  else
    ID="${create_new_session}:"
  fi
  ID="$(echo $ID | fzf | cut -d: -f1)"
  if [[ "$ID" == "${create_new_session}" ]]; then
    tmux_new_session
  elif [[ -n "$ID" ]]; then
    if [[ -n $TMUX ]]; then
      tmux switch-client -t "$ID"
    else
      tmux attach-session -t "$ID"
    fi
  else
    : # Start terminal normally
  fi
}

tmux_base_session(){
# create base session, then prompt for others
client_cnt="$(tmux list-clients 2>/dev/null | wc -l)"
if [[ $client_cnt -eq 0 ]]; then
  tmux -2 new-session -d -s z
  tmux -2 attach-session -t z
else
  tmux_sessions
fi
}

if [[ -z $TMUX ]]; then
  tmux_base_session
fi
