#!/usr/bin/env bash

# Checking if we are sourced
# see: https://stackoverflow.com/questions/2683279/how-to-detect-if-a-script-is-being-sourced
([[ -n $ZSH_EVAL_CONTEXT && $ZSH_EVAL_CONTEXT =~ :file$ ]] || 
[[ -n $BASH_VERSION ]] && (return 0 2>/dev/null)) && _GOTO_IS_SOURCED=0 || _GOTO_IS_SOURCED=1



function _goto_main {
    local PROJECT PROJECTFILE URI

    # If goto is  run in sourced mode, contiune.
    # Else: print warning. NO EXIT statement.

    if [[ $_GOTO_IS_SOURCED -eq 0 ]]; then

        # GOTOPATH may be set from environment, 
        # if not default to ~/.goto
        if [[ -z "$GOTOPATH" ]]; then
            GOTOPATH="${HOME}/.goto"
        fi


        PROJECT=$(cat "${GOTOPATH}/active-project")
        PROJECTFILE="${GOTOPATH}/projects/${PROJECT}.json"

        # Catching deactivated state
        # TODO: make a better way to print to stderr
        if [ -z "$PROJECT" ]; then
            echo "Ah hoy!" >&2
            echo >&2
            echo "Goto has no project context set." >&2
            echo >&2
            echo "An example project is bundled with goto, it is called goto." >&2
            echo "You may try  it by typing:" >&2
            echo >&2
            echo "     project goto" >&2
            echo >&2
            echo "Other usefull commands to work with projects:" >&2
            echo "    create project:   project add <project-name>" >&2
            echo "    more help:        project help" >&2

            
            return 1
        fi

        # Special case 1 (goto cd <magicword>)
        if [ "$1" = "cd" ]; then
                # hack to cd in this shell to the ouput of goto show <magicword>
                URI=$(goto show "$2")
                cd "$URI" || echo "Ah hoy - tried to cd to a non-existent path: $URI" >&2
            return 0
        fi


        # Special case 2  (goto <magicword>)
        if [ "$#" -eq 1 ]; then

            # if run like: goto <magicword> 
            URI=$(goto show "$1")

            # if path is folder, cd to folder
            if [ -d "$URI" ]; then
                cd "$URI" || echo "Ah hoy - tried to cd to a non-existent path: $URI" >&2
                return 0

            # if path is file, open file
            elif [ -f "$URI" ]; then
                goto open "$1"
                return 0
            fi
        fi

        # General case
        if [ -n "$(command -v the_real_goto.py)" ]; then
            the_real_goto.py "$PROJECTFILE" "$@"
        else
            echo "Error the_real_goto.py not found" >&2
            return 1
        fi

    else
        echo "Ah hoy!" >&2
        echo >&2
        echo "In order to make goto work properly, run this command now:" >&2
        echo >&2
        echo "       install_goto" >&2
        echo >&2
        exit 1
    fi
}

_goto_main "$@"
