#!/usr/local/bin/bash
#!/usr/bin/env bash

# --------------------------------
# QWERTY - Bash Text Editor
# --------------------------------

# Tab configuration
TAB_WIDTH=4

# Save original terminal settings
OLD_STTY=$(stty -g)

# --------------------------------
# File handling
# --------------------------------

filename="${1:-untitled.txt}"
buffer=()

if [[ -f "$filename" ]]; then
    while IFS= read -r line || [[ -n "$line" ]]; do
        buffer+=("$line")
    done < "$filename"
else
    buffer=("")
fi

if (( ${#buffer[@]} == 0 )); then
    buffer=("")
fi

modified=0

# --------------------------------
# Cursor and scrolling
# --------------------------------

cursor_x=0
cursor_y=0

scroll_x=0
scroll_y=0

# --------------------------------
# Cut buffer
# --------------------------------

cut_buffer=""
cut_available=0

# --------------------------------
# Terminal dimensions
# --------------------------------

screen_rows=$(tput lines)
screen_cols=$(tput cols)

# --------------------------------
# Rendering cache
# --------------------------------

last_doc_rows=()
last_status=""
last_help=""

last_screen_rows=0
last_screen_cols=0

# --------------------------------
# Terminal cleanup
# --------------------------------

cleanup() {

    stty "$OLD_STTY"

    printf '\033[?25h'
    printf '\033[?7h'
    printf '\033[?1049l'
    printf '\033[0m'
}

trap cleanup EXIT

# Enable immediate keyboard input
stty -echo -icanon min 1 time 0

# Enter alternate screen
printf '\033[?1049h'

# Disable automatic wrapping
printf '\033[?7l'

# Hide cursor
printf '\033[?25l'

# --------------------------------
# Save function
# --------------------------------

save_file() {

    if printf '%s\n' "${buffer[@]}" > "$filename"; then
        modified=0
        return 0
    else
        return 1
    fi
}

# --------------------------------
# Go to line function
# --------------------------------

go_to_line() {

    local target_line="$1"

    if [[ ! "$target_line" =~ ^[0-9]+$ ]]; then
        printf '\a'
        return
    fi

    target_line=$((10#$target_line))

    if (( target_line < 1 || target_line > ${#buffer[@]} )); then
        printf '\a'
        return
    fi

    cursor_y=$((target_line - 1))
    cursor_x=0
}

# --------------------------------
# Keep cursor inside buffer
# --------------------------------

adjust_cursor() {

    if (( cursor_y < 0 )); then
        cursor_y=0
    fi

    if (( cursor_y >= ${#buffer[@]} )); then
        cursor_y=$((${#buffer[@]} - 1))
    fi

    if (( cursor_x < 0 )); then
        cursor_x=0
    fi

    if (( cursor_x > ${#buffer[cursor_y]} )); then
        cursor_x=${#buffer[cursor_y]}
    fi
}

# --------------------------------
# Adjust visible screen area
# --------------------------------

adjust_scroll() {

    local text_rows=$((screen_rows - 2))

    if (( text_rows < 1 )); then
        text_rows=1
    fi

    # Vertical scrolling

    if (( cursor_y < scroll_y )); then
        scroll_y=$cursor_y
    fi

    if (( cursor_y >= scroll_y + text_rows )); then
        scroll_y=$((cursor_y - text_rows + 1))
    fi

    # Horizontal scrolling

    if (( cursor_x < scroll_x )); then
        scroll_x=$cursor_x
    fi

    if (( cursor_x >= scroll_x + screen_cols )); then
        scroll_x=$((cursor_x - screen_cols + 1))
    fi
}

# --------------------------------
# Screen rendering
# --------------------------------

render() {

    local i
    local line_number
    local visible
    local status
    local status_text
    local help_text
    local text_rows

    # Get current terminal dimensions
    screen_rows=$(tput lines)
    screen_cols=$(tput cols)

    adjust_cursor
    adjust_scroll

    text_rows=$((screen_rows - 2))

    if (( text_rows < 1 )); then
        text_rows=1
    fi

    # Hide cursor while updating display
    printf '\033[?25l'

    # Detect terminal resize
    if (( screen_rows != last_screen_rows ||
          screen_cols != last_screen_cols )); then

        printf '\033[2J'

        last_doc_rows=()
        last_status=""
        last_help=""

        last_screen_rows=$screen_rows
        last_screen_cols=$screen_cols
    fi

    # --------------------------------
    # Draw document rows
    # --------------------------------

    for ((i=0; i<text_rows; i++)); do

        line_number=$((scroll_y + i))

        visible=""

        if (( line_number < ${#buffer[@]} )); then

            visible="${buffer[line_number]:scroll_x:screen_cols}"

        fi

        # Only redraw changed rows
        if [[ "${last_doc_rows[i]-}" != "$visible" ]]; then

            printf '\033[%d;1H\033[2K' "$((i + 1))"

            printf '%s' "$visible"

            last_doc_rows[i]="$visible"
        fi

    done

    # --------------------------------
    # Status bar
    # --------------------------------

    if (( modified )); then
        status="Modified"
    else
        status="Saved"
    fi

    status_text="QWERTY | $filename | Line: $((cursor_y + 1)) | Column: $((cursor_x + 1)) | $status"

    if [[ "$status_text" != "$last_status" ]]; then

        printf '\033[%d;1H\033[2K' "$((screen_rows - 1))"

        printf '%s' "${status_text:0:screen_cols}"

        last_status="$status_text"
    fi

    # --------------------------------
    # Help bar
    # --------------------------------

    help_text="Ctrl+O: Save | Ctrl+X: Exit | Ctrl+K: Cut | Ctrl+U: Paste | Ctrl+/: Go To Line"

    if [[ "$help_text" != "$last_help" ]]; then

        printf '\033[%d;1H\033[2K' "$screen_rows"

        printf '%s' "${help_text:0:screen_cols}"

        last_help="$help_text"
    fi

    # --------------------------------
    # Position editing cursor
    # --------------------------------

    printf '\033[%d;%dH' \
        "$((cursor_y - scroll_y + 1))" \
        "$((cursor_x - scroll_x + 1))"

    # Show cursor
    printf '\033[?25h'
}

# --------------------------------
# Main editor loop
# --------------------------------

while true; do

    render

    IFS= read -rsn1 key

    case "$key" in

        # Ctrl+X: Exit
        $'\x18')

            if (( modified )); then

                printf '\033[%d;1H\033[2K' "$screen_rows"
                printf 'Unsaved changes! Save? (y/n/c) '

                IFS= read -rsn1 answer

                case "$answer" in

                    y|Y)
                        if save_file; then
                            break
                        fi
                        ;;

                    n|N)
                        break
                        ;;

                esac

            else
                break
            fi
            ;;

        # Ctrl+O: Save
        $'\x0f')

            if ! save_file; then
                printf '\a'
            fi
            ;;

        # Ctrl+K: Cut current line
        $'\x0b')

            cut_buffer="${buffer[cursor_y]}"
            cut_available=1

            if (( ${#buffer[@]} > 1 )); then

                buffer=(
                    "${buffer[@]:0:cursor_y}"
                    "${buffer[@]:$((cursor_y + 1))}"
                )

            else
                buffer[cursor_y]=""
            fi

            cursor_x=0
            modified=1
            ;;

        # Ctrl+U: Paste cut line
        $'\x15')

            if (( cut_available )); then

                buffer=(
                    "${buffer[@]:0:cursor_y}"
                    "$cut_buffer"
                    "${buffer[@]:cursor_y}"
                )

                ((cursor_y++))
                cursor_x=0
                modified=1
            fi
            ;;

        # Ctrl+/: Go to line
        $'\x1f')

            printf '\033[%d;1H\033[2KGo to line: ' "$screen_rows"

            target_line=""

            while true; do

                IFS= read -rsn1 input_char

                case "$input_char" in

                    $'\r'|$'\n'|'')
                        break
                        ;;

                    $'\x7f'|$'\x08')

                        if [[ -n "$target_line" ]]; then

                            target_line="${target_line%?}"

                            printf '\b \b'

                        fi
                        ;;

                    [0-9])

                        target_line+="$input_char"

                        printf '%s' "$input_char"
                        ;;

                    $'\x1b')

                        target_line=""
                        break
                        ;;

                esac

            done

            if [[ -n "$target_line" ]]; then
                go_to_line "$target_line"
            fi
            ;;

        # Tab: Insert four spaces
        $'\t')

            line="${buffer[cursor_y]}"

            left="${line:0:cursor_x}"
            right="${line:cursor_x}"

            spaces=""

            for ((i=0; i<TAB_WIDTH; i++)); do
                spaces+=" "
            done

            buffer[cursor_y]="${left}${spaces}${right}"

            ((cursor_x+=TAB_WIDTH))
            modified=1
            ;;

        # Enter: New line
        ''|$'\r')

            line="${buffer[cursor_y]}"

            left="${line:0:cursor_x}"
            right="${line:cursor_x}"

            buffer=(
                "${buffer[@]:0:cursor_y}"
                "$left"
                "$right"
                "${buffer[@]:$((cursor_y + 1))}"
            )

            ((cursor_y++))
            cursor_x=0
            modified=1
            ;;

        # Backspace
        $'\x7f'|$'\x08')

            if (( cursor_x > 0 )); then

                line="${buffer[cursor_y]}"

                left="${line:0:$((cursor_x - 1))}"
                right="${line:cursor_x}"

                buffer[cursor_y]="${left}${right}"

                ((cursor_x--))
                modified=1

            elif (( cursor_y > 0 )); then

                previous="${buffer[cursor_y - 1]}"
                current="${buffer[cursor_y]}"

                cursor_x=${#previous}

                buffer[cursor_y - 1]="${previous}${current}"

                buffer=(
                    "${buffer[@]:0:cursor_y}"
                    "${buffer[@]:$((cursor_y + 1))}"
                )

                ((cursor_y--))
                modified=1

            fi
            ;;

        # --------------------------------
        # Arrow keys
        # --------------------------------

        $'\x1b')

            IFS= read -rsn1 -t 0.1 key2 || true
            IFS= read -rsn1 -t 0.1 key3 || true

            case "$key2$key3" in

                # Up
                "[A")

                    if (( cursor_y > 0 )); then
                        ((cursor_y--))
                    fi
                    ;;

                # Down
                "[B")

                    if (( cursor_y < ${#buffer[@]} - 1 )); then
                        ((cursor_y++))
                    fi
                    ;;

                # Right: Next line at end of current line
                "[C")

                    if (( cursor_x < ${#buffer[cursor_y]} )); then

                        ((cursor_x++))

                    elif (( cursor_y < ${#buffer[@]} - 1 )); then

                        ((cursor_y++))
                        cursor_x=0

                    fi
                    ;;

                # Left: Previous line at beginning of current line
                "[D")

                    if (( cursor_x > 0 )); then

                        ((cursor_x--))

                    elif (( cursor_y > 0 )); then

                        ((cursor_y--))
                        cursor_x=${#buffer[cursor_y]}

                    fi
                    ;;

            esac
            ;;

        # --------------------------------
        # Character insertion
        # --------------------------------

        *)

            if [[ "$key" == [[:print:]] ]]; then

                line="${buffer[cursor_y]}"

                left="${line:0:cursor_x}"
                right="${line:cursor_x}"

                buffer[cursor_y]="${left}${key}${right}"

                ((cursor_x++))
                modified=1

            fi
            ;;

    esac

done
