#!/usr/bin/env sh

# Dmenu for opening videos with youtube-viewer.
# MUST HAVE the *ID* at the end of custom_layout_format in youtube-viewer.conf.
# Example:
# custom_layout_format  => "*TITLE*  (*AUTHOR*)  [*TIME*]  *ID*"

# MIT License
#
# Copyright (c) 2020 Alexander Chaplin Braz
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

### Add subscription system with sxiv for looking through video thumbnails
### and managing the videos.
### Set youtube-viewer arguments as variables to be able to select them like
### tags for a custom search.
### Implement search history for quickly searching again.

ScriptName=${0##*/}
Version=0.0.1

# Compose the help message:
HelpMessage="$ScriptName - Version: $Version
Creator: Alexander Chaplin Braz (https://alexchaplinbraz.com)
License: MIT

Usage: $ScriptName

MUST HAVE the *ID* at the end of custom_layout_format in youtube-viewer.conf.
Example:
custom_layout_format  => \"*TITLE*  (*AUTHOR*)  [*TIME*]  *ID*\"
"

case $1 in
    -h|--help) printf '%s' "$HelpMessage"; exit 0;;
    -v|--version) printf '%s - Version: %s\n' "$ScriptName" "$Version"; exit 0;;
esac

error() { printf 'ERROR: %s\n' "$1" 1>&2; }

suggest_help_and_exit() {
    printf "Try '%s --help' for more information.\n" "$ScriptName" 1>&2
    exit 1
}

YTURL='https://www.youtube.com/watch?v='

MenuSimple='1. Simple search.'
MenuHistory='2. History.'
MenuPlaylist='3. Playlist search.'
MenuChannel='4. Channel search.'

ChosenMenu=$(printf '%s\n%s\n%s\n%s' \
    "$MenuSimple" \
    "$MenuHistory" \
    "$MenuPlaylist" \
    "$MenuChannel" \
    | dmenu -i -l 10 -p "$ScriptName:")

if [ "$ChosenMenu" = "$MenuSimple" ]; then
    Search=$(printf '' | dmenu -p 'Simple search:')
    [ -z "$Search" ] && exit 1

    printf '%s\n' "$Search" >> "$LSHARE/dytsearchhistory"

    YTID=$(youtube-viewer --no-interactive "$Search" \
        | sed '/^$/d' \
        | nl -n ln \
        | dmenu -i -l 30 -p 'Select video:')
    [ -z "$YTID" ] && exit 1

    printf '%s\n' "$YTID" >> "$LSHARE/dytvideohistory"

    mpv "$YTURL${YTID##* }"

elif [ "$ChosenMenu" = "$MenuHistory" ]; then
    HistoryMenu=$(printf '1. Search history.\n2. Video history.' \
        | dmenu -i -l 10 -p 'Which history?')

    if [ "$HistoryMenu" = '1. Search history.' ]; then
        Search=$(cat "$LSHARE/dytsearchhistory" \
            | awk '{a[i++]=$0} END {for (j=i-1; j>=0;) print a[j--] }' \
            | dmenu -i -l 30 -p 'Select previous search:')
        [ -z "$Search" ] && exit 1

        printf '%s\n' "$Search" >> "$LSHARE/dytsearchhistory"

        YTID=$(youtube-viewer --no-interactive "$Search" \
            | sed '/^$/d' \
            | nl -n ln \
            | dmenu -i -l 30 -p 'Select video:')

        printf '%s\n' "$YTID" >> "$LSHARE/dytvideohistory"

    elif [ "$HistoryMenu" = '2. Video history.' ]; then
        YTID=$(cat "$LSHARE/dytvideohistory" \
            | awk '{a[i++]=$0} END {for (j=i-1; j>=0;) print a[j--] }' \
            | dmenu -i -l 30 -p 'Select previous video:')

    else
        exit 1
    fi
    [ -z "$YTID" ] && exit 1

    mpv "$YTURL${YTID##* }"

elif [ "$ChosenMenu" = "$MenuPlaylist" ]; then
    ### Can't find how to change the format for anything other than video list
    ### so it's broken. Can parse it in another way, but it's ugly.
    ### Can also just open youtube-viewer as intended.
    exit 1

    Search=$(printf '' | dmenu -p 'Playlist search:')
    [ -z "$Search" ] && exit 1

    YTID=$(youtube-viewer --no-interactive -sp "$Search" \
        | sed '/^$/d' \
        | dmenu -i -l 30 -p 'Select playlist:')
    [ -z "$YTID" ] && exit 1

    mpv "$YTURL${YTID##* }"

elif [ "$ChosenMenu" = "$MenuChannel" ]; then
    exit 1

elif [ -z "$ChosenMenu" ]; then
    exit 1
else
    error 'invalid selection.'
    suggest_help_and_exit
fi
nn
