#!/usr/bin/env dash

project0open_current_context_in_browser() {
    current_context="$(utils0get_current_context)"
    [ "$current_context" ] || die "No current context to use"
    project0open_context_in_browser "$(utils0context2project "$current_context")"
}

project0open_project_in_browser() {
    project="$1"
    [ "$project" ] || die "BUG: No context supplied to project0open_context_in_browser"

    old_context="$(utils0get_current_context)"
    # We have ensured that only one task may be active
    old_started_task="$(task +ACTIVE _ids)"

    tracking="$(mktmp)"
    task "project:$project" _ids | xargs --no-run-if-empty task _zshids >"$tracking"
    task context "$(utils0project2context "$project")"

    while read -r description; do
        desc="$(echo "$description" | awk -F: '{print $2}')"
        if [ "$desc" = "tracking" ]; then
            task_id="$(echo "$description" | awk -F: '{print $1}')"
            notify-send "(Neorg)" "Starting task $project -> $desc"
            task start "$task_id"
            break
        fi
    done <"$tracking"

    firefox -P "$project"

    task stop "$task_id"
    [ "$old_started_task" ] && task start "$old_started_task"

    if [ "$old_context" ]; then
        task context "$old_context"
    else
        task context none
    fi
}