#!/bin/bash

source /usr/share/mb-jgtools/jgtools.inc


me=${0##*/}
CONKYDIR="$HOME/.config/conky"
CFG_FILE=~/.config/mabox/mabox-todo.conf
TODO_DIR=~/.todo

source <(grep = $CFG_FILE)

sleep .1
#notify-send.sh aaa "${0} ${1} ${me}"
# LANG
case "$LANG" in
    pl*)
    _TODOLIST="Lista zadań"
    _ADD_NEWTASK="Dodaj <b>nowe</b> zadanie..."
    _TASK="zadanie"
    _DEPRIORITIZE="Usuń priorytet"
    _PRIA="priorytet <b>(A)</b>"
    _PRIB="priorytet <b>(B)</b>"
    _PRIC="priorytet <b>(C)</b>"
    _MARK_DONE="Oznacz jako zrobione"
    _EDIT="Edytuj"
    _MOVE_TO="Przenieś do..."
    _MOVE_TASK_TO="Przenieś zadanie do..."
    _DEL_TASK="Usuń zadanie"
    _ARCHIVE="Archiwizuj (usuń wszystkie wykonane zadania)"
    _NOTES_FOR="<b>Notatki</b> dla"
    _SWITCHTO="Przełącz do listy zadań"
    _TASKS="zadania"
    _NEW_TODOLIST="Utwórz <b>nową Listę zadań</b>..."
    _IN_TEXTEDITOR="w edytorze tekstu"
    _ADD_NOTES="Dodaj notatki (cherrytree) do"
    _NEED_NOTES="Potrzebujesz notatek do listy zadań? Zainstaluj Cherrytree"
    _ADD_MENU="Dodaj własne menu do"
    _EDIT_MENU="Edytuj własne menu do"
    _DELETE_MENU="Usuń własne menu do"
    _DANGERZONE="Niebezpieczna strefa"
    _DELETE="Usuń"
    _LIST_AND_ALL=" i powiązane pliki"
    _AREYOU_SURE="Czy aby na pewno?"
    _YES_DELETE="Tak, usuń"
    _CONKY_SETTINGS_LONG="Ustawienia Widżetu Conky"
    _CONKY_SETTINGS="Ustawienia widżetu Conky"
    _CONKY_POS="Pozycja, czcionka, kolory..."
    _CLEAR_FILTER="Wyczyśc filtr"
    _FILTERBY="Filtruj"
    _SH_CONKY="Pokaż/ukryj elementy w Conky"
    _SH_DONE="Pokaż zakończone zadania"
    _SH_PRIO="(A-C) priorytety"
    _SH_PROJ="+projekt"
    _SH_CONTEXT="@kontekst"
    _START_CONKY="Uruchom widżet Conky TODOList"
    _COMMANDS_FOR="Komendy dla"
    ;;

    *)
    _TODOLIST="TODO List"
    _ADD_NEWTASK="Add <b>new</b> task..."
    _TASK="task"
    _DEPRIORITIZE="Deprioritize"
    _PRIA="<b>(A)</b> priority"
    _PRIB="<b>(B)</b> priority"
    _PRIC="<b>(C)</b> priority"
    _MARK_DONE="Mark as done"
    _EDIT="Edit"
    _MOVE_TO="Move to..."
    _MOVE_TASK_TO="Move task to..."
    _DEL_TASK="Delete task"
    _ARCHIVE="Archive (remove all done tasks)"
    _NOTES_FOR="<b>Notes</b> for"
    _SWITCHTO="Switch to todolist"
    _TASKS="tasks"
    _NEW_TODOLIST="Create <b>New TODO List</b>..."
    _IN_TEXTEDITOR="in Text editor"
    _ADD_NOTES="Add hierarchical notes (cherrytree) to"
    _NEED_NOTES="Need notes for todolist? Install Cherrytree"
    _ADD_MENU="Add custom menu for"
    _EDIT_MENU="Edit custom menu for"
    _DELETE_MENU="Delete custom menu for"
    _DANGERZONE="Danger Zone"
    _DELETE="Delete"
    _LIST_AND_ALL="and all related files"
    _AREYOU_SURE="Are you sure?"
    _YES_DELETE="Yes, delete"
    _CONKY_SETTINGS_LONG="Display settings/filter"
    _CONKY_SETTINGS="Conky widget settings"
    _CONKY_POS="Position, font, colors..."
    _CLEAR_FILTER="Clear filter"
    _FILTERBY="Filter by"
    _SH_CONKY="Show/hide some elements in Conky"
    _SH_DONE="Show done tasks"
    _SH_PRIO="(A-C) priority"
    _SH_PROJ="+project"
    _SH_CONTEXT="@context"
    _START_CONKY="Start TODOList conky widget"
    _COMMANDS_FOR="Custom commands for"
    ;;
esac

#MENU 
prettyname=${filename//_/ }
out+=("^sep($_TODOLIST: <b>${prettyname}</b>)")
out+=("<big></big>   $_ADD_NEWTASK,mabox-todo.sh addtask && ${0} center")

out+=("^sep()")

s=0
i=0
dirty=0

# Dostępne pliki
readarray -t files < <(mabox-todo.sh listfiles)
readarray -t contexts < <(mabox-todo.sh listcon)
readarray -t projects < <(mabox-todo.sh listproj)

# Lista zadań
while read -r line
do
[[ "$line" = "--" ]] && s=1 && continue;
((i++))
if [ "$s" = 1 ];then
 out+=("^sep(<i>${line}</i>)")
 else
#notify-send.sh MSG "${line}"
linia="${line}"
number=${linia#*>}
number=${number%%<*}
#notify-send.sh "${number}" "${line}"
#number=${line:21:2}
#notify-send.sh "${number}" "${line}"
#notify-send.sh "${number}" "${line:32:1}"

pri="([A-Z])"
line=${line/\<\/span\>\<\/span\>/\<\/span\>}
line=${line/\<\/span\> \<\/span\>/\<\/span\>}
line=${line/&/&amp;}

linia2="${line}"
iks=${linia#*span>} # pozbywamy sie początku
iks=${iks%%<*} # i reszty
[[ "$iks" == " x " ]] && ((dirty++)) #notify-send.sh "iks" "${iks}"
#[[ "${line:32:1}" = "x" || "${line:31:1}" = "x" ]] && ((dirty++))# && notify-send.sh "AAA" "<tt>${line}</tt>"
[[ "${dirty}" == "1" ]] && out+=("^sep(done tasks)")
out+=("\"\"\"${line}\"\"\",^checkout(${i})")
out2+=("^tag(${i})")
out2+=("^sep($_TODOLIST: <b>${prettyname}</b>)")
out2+=("^sep($_TASK: ${number})")
#out2+=("    <small>back to list</small>,^back()")
out2+=("^sep()")
out2+=("\"\"\"${line}\"\"\",geany -l ${number:-1} ${TODO_DIR}/${filename}.txt")
out2+=("^sep()")
if [ "$dirty" = "0" ];then
	if [ -z "${line##*$pri*}" ]; then
	out2+=(" $_DEPRIORITIZE,mabox-todo.sh dp ${number};${0} center")
	fi
    out2+=(" $_PRIA,mabox-todo.sh p ${number} A;${0} center")
	out2+=(" $_PRIB,mabox-todo.sh p ${number} B;${0} center")
	out2+=(" $_PRIC,mabox-todo.sh p ${number} C;${0} center")
    out2+=("^sep()")
out2+=("<big></big>   $_MARK_DONE,mabox-todo.sh -a -f -n done ${number};${0} center" "^sep()")
fi
out2+=("<big></big>   $_EDIT $_TASK,geany -l ${number:-1} ${TODO_DIR}/${filename}.txt")

if [ "${#files[@]}" -gt "1" ];then
    out2+=("<big>󱉆</big>   $_MOVE_TO,^checkout(file${number})")
    out3+=("^tag(file${number})")
    out3+=("^sep($_MOVE_TASK_TO)")
    for file in "${files[@]}"
        do
        prettyfile=${file//_/ }
        [[ "$file" != "$filename" ]] && out3+=("${prettyfile},mabox-todo.sh -f -n move ${number} ${file}.txt ${filename}.txt;${0} center")
    done
fi

#out2+=("    <small>back to list</small>,^back()")
out2+=("^sep()")
out2+=("<big></big>   $_DEL_TASK,mabox-todo.sh -f -n del ${number};${0} center")
fi
done <<< $(mabox-todo.sh -d ~/.config/todo/config-jgmenu ls)
[[ "$dirty" > "0" ]] && out+=("<big>󱝧</big>   $_ARCHIVE,mabox-todo.sh -f archive; ${0} center" "^sep()")


out+=("<big></big>   $_TODOLIST: <b>${prettyname}</b>...,^checkout(files)")
[[ -f "${TODO_DIR}/${filename}.ctb" ]] && out+=("^sep()" "<big>󱁂</big>   $_NOTES_FOR ${prettyname},cherrytree ${TODO_DIR}/${filename}.ctb")
out2+=("^tag(files)")

if [ "${#files[@]}" -gt "1" ];then
    out2+=("^sep($_SWITCHTO:)")
    while read -r line
    do
    prettyline=${line//_/ }
    tasks=$(cat ~/.todo/${line}.txt |wc -l)
    if [ "$line" = "${filename}" ];then
    out2+=("<big>${ron}</big>   <b>${prettyline}</b> <small><i>($_TASKS ${tasks})</i></small> ,${0} center")
    else
    out2+=("<big>${roff}</big>   ${prettyline} <small><i>($_TASKS ${tasks})</i></small> ,mabox-todo.sh s $line;${0} center")
    fi
    done <<< $(mabox-todo.sh listfiles)
fi
out2+=("^sep()")
out2+=("<b></b>   $_NEW_TODOLIST,mabox-todo.sh addfile && ${0} center")
out2+=("^sep($_TODOLIST: ${prettyname})")
out2+=("<big></big>   $_EDIT <b>${prettyname}</b>.txt $_IN_TEXTEDITOR,xdg-open ${TODO_DIR}/${filename}.txt")


### Cherrytree
if hash cherrytree 2>/dev/null
then
    if [[ -f "${TODO_DIR}/${filename}.ctb" ]];then
    :
    #out2+=("Edit notes,cherrytree ${TODO_DIR}/${filename}.ctb")
    else
    out2+=("<big></big>   $_ADD_NOTES <b>${prettyname}</b>,mabox-todo.sh addnotes ${filename};${0}")
    fi
else
out2+=("<big>󱁂</big>   $_NEED_NOTES,pamac-installer cherrytree")
fi
## Custom Menu
if [[ -f "${TODO_DIR}/${filename}.csv" ]];then
out2+=("$_EDIT_MENU <b>${prettyname}</b>,xdg-open ${TODO_DIR}/${filename}.csv")
out2+=("$_DELETE_MENU <b>${prettyname}</b>,rm -f ${TODO_DIR}/${filename}.csv;${0} center")
else
out2+=("<big>󰍜</big>   $_ADD_MENU <b>${prettyname}</b>,mabox-todo.sh addmenu ${filename}")
fi



#out2+=("   ,^back()")
out2+=("^sep($_DANGERZONE)")
out2+=("<big></big>   $_DELETE <b>${prettyname}</b> $_LIST_AND_ALL,^checkout(delproj)")
out3+=("^tag(delproj)")
out3+=("^sep($_AREYOU_SURE)")
out3+=("\"\"\"$_YES_DELETE <b>${prettyname}</b> $_LIST_AND_ALL\"\"\",mabox-todo.sh removeproject ${filename};${0} center")


### for Conky only if running
if pgrep -f 'conky.*conky/TODOlist' 2> /dev/null;then
out+=("^sep(Conky widget)")
out+=("$_CONKY_SETTINGS_LONG,^checkout(display)")
out+=("\"\"\"$_CONKY_POS\"\"\",^pipe(conkyctl single ~/.config/conky/TODOlist_mbcolor.conkyrc)")
# DISPLAY SETTINGS SUBMENU
out2+=("^tag(display)")
out2+=("^sep($_CONKY_SETTINGS)")
[[ "$filter" != "" ]] && out2+=("<big></big>  $_CLEAR_FILTER ($filter),mb-setvar filter= ${CFG_FILE};${0} center")

# Projects
if (( ${#projects[@]} == 0 )); then
    : #empty
else
    out2+=("^sep($_FILTERBY)")
	for proj in "${projects[@]}"
	do
	[[ "$filter" == "$proj" ]] && out2+=("<big>${ron}</big>  <span bgcolor='#CCCCCC' fgcolor='purple'><b> ${proj} </b></span>,mb-setvar filter= ${CFG_FILE};${0} center") || out2+=("<big>${roff}</big>  <span bgcolor='#CCCCCC' fgcolor='purple'> ${proj} </span>,mb-setvar filter=${proj} ${CFG_FILE};${0} center")
	done
fi

if (( ${#contexts[@]} == 0 )); then
    : #empty
else
	out2+=("^sep()")
	for context in "${contexts[@]}"
	do
	[[ "$filter" == "$context" ]] && out2+=("<big>${ron}</big>  <span fgcolor='green' bgcolor='#EEEEEE'><b> ${context} </b></span>,mb-setvar filter= ${CFG_FILE};${0} center") || out2+=("<big>${roff}</big>  <span fgcolor='green' bgcolor='#EEEEEE'> ${context} </span>,mb-setvar filter=${context} ${CFG_FILE};${0} center")
	done
fi

out2+=("^sep($_SH_CONKY)")
[[ "$hide_done" = "y" ]] && out2+=("<big>${cboff}</big>   $_SH_DONE,mb-setvar hide_done=n ${CFG_FILE}; ${0} center") || out2+=("<big>${cbon}</big>   $_SH_DONE,mb-setvar hide_done=y ${CFG_FILE}; ${0} center")
[[ "$hide_priority" = "y" ]] && out2+=("<big>${cboff}</big>   $_SH_PRIO,mb-setvar hide_priority=n ${CFG_FILE}; ${0} center") || out2+=("<big>${cbon}</big>   $_SH_PRIO ,mb-setvar hide_priority=y ${CFG_FILE}; ${0} center")
[[ "$hide_project" = "y" ]] && out2+=("<big>${cboff}</big>   $_SH_PROJ,mb-setvar hide_project=n ${CFG_FILE}; ${0} center") || out2+=("<big>${cbon}</big>   $_SH_PROJ,mb-setvar hide_project=y ${CFG_FILE}; ${0} center")
[[ "$hide_context" = "y" ]] && out2+=("<big>${cboff}</big>   $_SH_CONTEXT,mb-setvar hide_context=n ${CFG_FILE}; ${0} center") || out2+=("<big>${cbon}</big>   $_SH_CONTEXT,mb-setvar hide_context=y ${CFG_FILE}; ${0} center")

else
out+=("$_START_CONKY,conkyctl startone ${HOME}/.config/conky/TODOlist_mbcolor.conkyrc;${0}")
fi


# HELP
#out+=("^sep()")
#out+=("<big></big>   About and Help,${0} center")
#out+=("󰞷   CLI usage Help,^term(mabox-todo.sh help)")



#Custom COMMANDS from CSV file
if [ -f ${TODO_DIR}/${filename}.csv ]; then
   LINES=$(grep  -Ev "^#|^$" ${TODO_DIR}/${filename}.csv|wc -l)
if [ ${LINES} != 0 ]; then
out+=("^sep($_COMMANDS_FOR <b>${prettyname}</b>)")
fi
fi



CONFIG_FILE=$(mktemp)
MENU_ITEMS=$(mktemp)
trap "rm -f ${CONFIG_FILE} ${MENU_ITEMS}" EXIT
POSITION_MODE=center
CENTER=""
if [ "$1" = "center" ]; then 
POSITION_MODE="center"
fi
MENU_HALIGN="center"
MENU_VALIGN="top"
menu_margin_x=90
MENU_MARGIN_Y=90
HIDE_BACK_ITEMS=1
MENU_PADDING_TOP=${jgtools_padding:-0}
JGWIDTH=180
TABS=90
jgmenu_icon_size=0
menu_font_size=11
jgmenu_font="Noto Sans 11"
jgtools_border=12
jgtools_padding=12

mkconfigfile
echo menu_height_mode=dynamic >> ${CONFIG_FILE}
echo hide_back_items=0 >> ${CONFIG_FILE}

cat <<EOF > ${MENU_ITEMS}
$(printf '%s\n' "${out[@]}")
. ${TODO_DIR}/${filename}.csv
$(printf '%s\n' "${out2[@]}")
$(printf '%s\n' "${out3[@]}")
EOF

cat "${MENU_ITEMS}"
#cat /home/napcok/.config/conky/menuscripts/TODOtxt.csv
jgmenu --config-file=${CONFIG_FILE} --csv-file=${MENU_ITEMS}  2>/dev/null
