#!/usr/bin/env zsh
# Copyrights 2022 Aman Mehra.
# Check ../LICENSE_CODE, ../LICENSE_ART, and ../LICENSE_ADDENDUM_CFLA
# files to know the terms of license
# License files are also on github: https://github.com/poetaman/arttime

autoload -Uz is-at-least
if ! is-at-least "5.7"; then
    echo "Error: your zsh version $ZSH_VERSION is less than the required version: 5.7"
    exit 1
fi

arttime_version="2.3.4"

zmodload zsh/zutil
zmodload zsh/terminfo
setopt extendedglob

if is-at-least "5.8"; then
    zparseoptscmd='zparseopts -D -E -F - '
else
    zparseoptscmd='zparseopts -D -E - '
fi

$(printf "$zparseoptscmd") \
   t:=title_arg \
   s:=subtitle_arg \
   a:=artname_arg \
   -random=random_arg \
   h=help_arg \
   m=man_arg \
   -tc:=titlecolor_arg \
   -sc:=subtitlecolor_arg \
   -ac:=artcolor_arg \
   -theme:=theme_arg \
   -width:=width_arg \
   -height:=height_arg \
   -style:=style_arg \
   -debug=debug_arg \
   -version=version_arg \
   -help=help_arg \
   -man=man_arg \
   || return

if [[ "${#@}" != "0" ]]; then
    printf "Error: artprint does not understand the following part of passed options,\n    "
    printf ' %s ' "[1m[4m$@[0m"
    printf '\n%s\n' "check the valid options by invoking artprint with --help"
    exit 1
fi

function printhelp {
read -r -d '' VAR <<-'EOF'
Usage:
    artprint [OPTION]...

Option summary:
    -a <name>
        name of a-art file from artdir
    -t <str>
        title message placed under art
    -s <str>
        sub-title message
    --random
        select random art from arttime's collection
    --ac <num>
        art color, value between 0-15
    --tc <num>
        title color, value between 0-15
    --sc <num>
        sub-title color, value between 0-15
    --theme <light|dark>
        theme
    --style <num>
        style number
    --width <num>
        page width
    --height <num>|"term"
        page height
    --version
        Print version number of *arttime*, and exit
    -m, --man
        Open artprint's manual
    -h, --help
        Print help string, and exit

For more information on artprint, try:
    $ artprint -m
    $ man artprint
EOF
echo $VAR
}

# directories
bindir="${0:A:h}"
artdir="$bindir/../share/arttime/textart"

if [[ ! -z $help_arg[-1] ]]; then
    printhelp
    exit 0
elif [[ ! -z $man_arg[-1] ]]; then
    unamestr="$(uname -a)"
    case "${unamestr}" in
        Linux*)
            if [[ "$unamestr" =~ ^.*[Mm]icrosoft.*$ ]]; then
                machine="WSL"
            else
                machine="Linux"
            fi
            ;;
        Darwin*)    machine="Darwin";;
        *BSD*)      machine="BSD";;
        *)          machine="UNKNOWN:${unamestr}";;
    esac
    docdir="$bindir/../share/arttime/doc"
    mandir="$bindir/../share/man/man1"
    if [[ -f $docdir/artprint.1.ans ]]; then
        if command -v less &>/dev/null; then
            LESS="" exec less -SRKP 'Press q to quit\. Use arrow keys, j/k, PageDown, PageUp to scroll\.' $docdir/artprint.1.ans
        elif command -v most &>/dev/null; then
            COLORTERM=16 exec most $docdir/artprint.1.ans
        else
            exec cat $docdir/artprint.1.ans
        fi
    fi
    if command -v less &>/dev/null; then
        export LESS=""
        export LESS_TERMCAP_md=$(echoti setaf 4; echoti bold)
        export LESS_TERMCAP_us=$(echoti setaf 5; echoti sitm 2>/dev/null)
        export LESS_TERMCAP_ue=$(echoti sgr0)
    fi
    export MANWIDTH=80
    export MANROFFOPT=""
    export GROFF_SGR=1
    if [[ -f $mandir/artprint.1.gz ]]; then
        if [[ $machine == "Linux" ]]; then
            export MANPAGER="less -SRK" 
            export MANLESS="Press q to quit\. Use arrow keys, j/k, PageDown, PageUp to scroll\."
            exec command man --nh --nj $mandir/artprint.1.gz
        elif [[ $machine == "Darwin" ]] && command -v gman &>/dev/null; then
            export MANPAGER="less -SRK" 
            export MANLESS="Press q to quit\. Use arrow keys, j/k, PageDown, PageUp to scroll\."
            exec command gman --nh --nj $mandir/artprint.1.gz
        elif command -v man &>/dev/null; then
            export MANPAGER="less -SRKP \"Press q to quit\. Use arrow keys, j/k, PageDown, PageUp to scroll\.\"" 
            exec command man $mandir/artprint.1.gz
        else
            echo "E: command 'man' not found"
            exit 1
        fi
    else
        echo "E: artprint manual not found"
        exit 1
    fi
elif [[ ! -z $version_arg[-1] ]]; then
    echo "$arttime_version"
    exit 0
fi

title="${title_arg[-1]}"
subtitle="${subtitle_arg[-1]}"
artcolor="${artcolor_arg[-1]}"
titlecolor="${titlecolor_arg[-1]}"
subtitlecolor="${subtitlecolor_arg[-1]}"
artname="${artname_arg[-1]}"
randomarg="${random_arg[-1]}"
theme="${theme_arg[-1]}"
widtharg="${width_arg[-1]}"
heightarg="${height_arg[-1]}"
style="${style_arg[-1]}"
debug="${debug_arg[-1]}"

if [[ $artname != "" && $randomarg != "" ]]; then
    echo "Error: options -a <artname> and --random should not be passed together."
    exit 1
fi

if [[ ! -z $debug ]]; then
    tchar="|"
else
    tchar=" "
fi

if [[ ! -z $randomarg ]]; then
    prevdir=$PWD
    cd $artdir
    defaultshuffle=(^tarot-*(.Nnoe['REPLY=$RANDOM']))
    cd $prevdir
    defaultart="$defaultshuffle[1]"
else
    defaultart="butterfly"
fi


if [[ -z $artname ]]; then
    artfile="$artdir/$defaultart"
else
    if [[ -f "${artname/#\~/$HOME}" ]]; then
        artfile="${artname/#\~/$HOME}"
    else
        artfile="$artdir/${artname}"
    fi
fi

if [[ ! -f "$artfile" ]]; then
    echo "W: file $artfile not found, no textart will be shown" >/dev/stderr
    artfile="/dev/null"
fi

art=$(tail -n +2 "$artfile")

if [[ -z $title ]]; then
    title=$(head -n1 "$artfile")
elif [[ $title = "-" ]]; then 
    title=""
fi

if [[ ! -z $widtharg ]]; then
    termwidth=$widtharg
else
    termwidth=$COLUMNS
fi

if [[ ! -z $heightarg ]]; then
    if [[ $heightarg ==  "term" ]]; then
        termheight=$LINES
    else
        termheight=$heightarg
    fi
else
    termheight="0"
fi

if ! command -v ansifilter &> /dev/null; then
    filterexternal="0"
    function findtextwidth {
        local textnoansi=$(sed -e 's/'$'\x1b''\[[0-9;]*m//g' <<<$1)
        echo "${#textnoansi}"
    }
else
    filterexternal="1"
    function findtextwidth {
        local textnoansi=$(ansifilter --ignore-csi <<<$1)
        echo "${#textnoansi}"
    }
fi

typeset -a textwidths
textwidth=0
textheight=0
linewidth=0
if [[ $filterexternal = "0" ]] then
    #textwidth=$(sed -e 's/\x1b\[[0-9;]*m//g' <<<$art | wc -L)
    #textheight=$(wc -l <<<$art)
    while IFS= read -r line; do
        linewidth=${#line}
        textwidths+=($linewidth)
        if [[ $linewidth -gt $textwidth ]]; then
            textwidth=$linewidth;
        fi;
        textheight=$((textheight+1))
    done <<<$(sed -e 's/'$'\x1b''\[[0-9;]*m//g' <<<$art);
else
    #textwidth=$(ansifilter --ignore-csi <<<$art | wc -L)
    #textheight=$(wc -l <<<$art)
    while IFS= read -r line; do
        linewidth=${#line}
        textwidths+=($linewidth)
        if [[ $linewidth -gt $textwidth ]]; then
            textwidth=$linewidth;
        fi;
        textheight=$((textheight+1))
    done <<<$(ansifilter --ignore-csi <<<$art);
fi

if [[ -z $title ]]; then
    if [[ -z $subtitle ]]; then
        shiftheight=$(((termheight-textheight-2)/2))
    else
        shiftheight=$(((termheight-textheight-4)/2))
    fi
else
    shiftheight=$(((termheight-textheight-6)/2))
fi

shiftwidth=$(((termwidth-textwidth)/2))

# Note: FreeBSD's pr doesn't accept 0 for value of argument -o, hence
# the prshiftopt instead of passing -o $shiftwidth when $shiftwidth is 0
if [[ ! $shiftwidth -gt 0 ]]; then
    shiftwidth=0
    prshiftopt=''
else
    prshiftopt='-o'"$shiftwidth"
fi

if [[ ! $shiftheight -gt 0 ]]; then
    shiftheight=0
fi

printf "%$((termwidth-1)).s$tchar\n" " " {0..$shiftheight}

if [[ -z $artcolor ]]; then
    if [[ -z "$theme" || "$theme" = "dark" ]]; then
        printf "\e[0m\e[38;5;1m" #\e[1m
    else
        printf "\e[0m\e[38;5;m" #\e[1m
    fi
else
    printf "\e[0m\e[38;5;${artcolor}m" #\e[1m
fi
typeset -i index
index=1
pr -t $prshiftopt <<<"$art" | while IFS= read -r line; do
    artlinewidth=$textwidths[$index]
    index=$((index+1))
    printf "%s%$((termwidth-shiftwidth-artlinewidth-1))s$tchar\n" "$line" " "
done

#echo "$textwidth, $shiftwidth"
if [[ $style = "0" || $style = "" ]]; then
    title="${title//❝ /\"}"
    title="${title// ❞/\"}"
    title="${title//“/\"}"
    title="${title//”/\"}"
    title="${title//—/-}"
    subtitle="${subtitle//❝/\"}"
    subtitle="${subtitle/❞/\"}"
    subtitle="${subtitle//“/\"}"
    subtitle="${subtitle//”/\"}"
    subtitle="${subtitle//—/-}"
else
    title="${title//“/❝}"
    title="${title//”/❞}"
    title="${title/#\"/❝ }"
    title="${title/\" \-/ ❞ —}"
    title="${title/%\"/ ❞}"
    subtitle="${subtitle//“/❝}"
    subtitle="${subtitle//”/❞}"
    subtitle="${subtitle/#\"/❝ }"
    subtitle="${subtitle/\" \-/ ❞ —}"
    subtitle="${subtitle/%\"/ ❞}"
fi


if [[ ! -z "$title" ]]; then
    titlewidth=$(findtextwidth $title)
    printf "%$((termwidth-1)).s$tchar\n" " "
    if [[ -z $titlecolor ]]; then
        if [[ -z "$theme" || "$theme" = "dark" ]]; then
            printf "\e[0m\e[38;5;2m"
        else
            printf "\e[0m\e[38;5;m"
        fi
    else
        printf "\e[0m\e[38;5;${titlecolor}m"
    fi
    shiftwidth=$(((termwidth-${titlewidth})/2))
    if [[ ! $shiftwidth -gt 0 ]]; then
        shiftwidth=0
    fi
    padwidth=$((termwidth-shiftwidth-${titlewidth}-1))
    if [[ ! $padwidth -gt 0 ]]; then
        padwidth=0
    fi
    tput_sitm=$(echoti sitm 2>/dev/null)
    printf "%${shiftwidth}s${tput_sitm}%${titlewidth}s\e[0m%${padwidth}s$tchar" " " "$title" " "
    #/usr/bin/fmt -c -w $termwidth <<< "$title"  | while IFS= read -r line; do
    #    printf "%s%$((termwidth-${#line}-1))s$tchar" "$line" " "
    #done
fi

if [[ ! -z "$subtitle" ]]; then
    subtitlewidth=$(findtextwidth $subtitle)
    #printf "%$((termwidth-1)).s$tchar\n" " "
    if [[ -z $subtitlecolor ]]; then
        if [[ -z "$theme" || "$theme" = "dark" ]]; then
            printf "\e[0m\e[38;5;6m"
        else
            printf "\e[0m\e[38;5;m"
        fi
    else
        printf "\e[0m\e[38;5;${subtitlecolor}m"
    fi
    shiftwidth=$(((termwidth-${subtitlewidth})/2))
    if [[ ! $shiftwidth -gt 0 ]]; then
        shiftwidth=0
    fi
    padwidth=$((termwidth-shiftwidth-${subtitlewidth}-1))
    if [[ ! $padwidth -gt 0 ]]; then
        padwidth=0
    fi
    printf "\n%${shiftwidth}s%${subtitlewidth}s%${padwidth}s$tchar" " " "$subtitle" " "
    #/usr/bin/fmt -c -w $termwidth <<< "$subtitle" | while IFS= read -r line; do
    #    printf "%s%$((termwidth-${#line}-1))s$tchar" "$line" " "
    #done
fi
#printf "%$((termwidth-1))s$tchar" " "
printf "[0m"
