#!/usr/bin/env bash

# This file is part of I38.
                                                                                                                                                                          
# I38 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation,
# either version 3 of the License, or (at your option) any later version.
                                                                                                                                                                          
# I38 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
                                                                                                                                                                          
# You should have received a copy of the GNU General Public License along with I38. If not, see <https://www.gnu.org/licenses/>.
                                                                                                                                                                          
 
add_bookmark() {
    while : ; do
        if [[ -r "${config}/surfraw/bookmarks" ]] && [[ -r "${config}/i3/bookmarks" ]]; then
            # Ask for the Bookmark Title, URL, and file selection using yad --form with radio buttons
            input=$(yad --form \
                        --title="I38 - Add Bookmark" \
                        --text="New Bookmark:" \
                        --field="Bookmark Title" \
                        --field="URL" \
                        --field="!Save As:CB" \
                        --field="Surfraw Bookmark":CHK \
                        --field="I38 Bookmark":CHK \
                        --button="OK:0" \
                        --button="Cancel:1" \
                        --selectable-labels \
                        --separator="|")
        else
            # Ask for the Bookmark Title and URL using yad --form without radio buttons
            input=$(yad --form \
                        --title="I38 - Add Bookmark" \
                        --text="New Bookmark:" \
                        --field="Bookmark Title" \
                        --field="URL" \
                        --button="OK:0" \
                        --button="Cancel:1" \
                        --selectable-labels \
                        --separator="|")
        fi
        yadCode="$?"

        # Check if the user pressed Cancel
        if [[ $yadCode -eq 1 ]]; then
            exit 0
        fi

        # Split the input into components
        IFS='|' read -r title url bookmarkFile <<< "$input"

        # Check if title or URL is empty
        if [[ -z "$title" || -z "$url" ]]; then
            yad --info --title="Add Bookmark" --text="Both Title and URL cannot be empty. Please try again."
            continue
        fi

        # Check for spaces in title and prompt user
        if [[ "$title" =~ \  ]] && [[ "$bookmarkFile" == "Surfraw Bookmark" ]]; then
            newTitle="${title//[[:space:]]/_}"
            yad --question --title="I38 - Bookmarks" --text="The title contains spaces, which have been converted to underscores: \"$newTitle\". Is this okay?"
            yadCode="$?"
            if [[ $yadCode -ne 0 ]]; then
                continue
            else
                title="$newTitle"
            fi
        fi

        # Determine the bookmarks file based on radio button selection
        if [[ -f "${config}/surfraw/bookmarks" ]] && [[ -f "${config}/i3/bookmarks" ]]; then
            if [[ "$bookmarkFile" == "Surfraw Bookmark" ]]; then
                bookmarksFile="${config}/surfraw/bookmarks"
            else
                bookmarksFile="${config}/i3/bookmarks"
            fi
        else
            bookmarksFile="${config}/i3/bookmarks"
        fi

        # Check for duplicates
        if grep -q "$url" "$bookmarksFile" ; then
            existingTitle=$(grep "$url" "$bookmarksFile" | cut -d' ' -f1)
        yad --form --title="I38 - Bookmarks" --selectable-labels --field="This site is already bookmarked as \"$existingTitle\".":LBL --button="OK:0"
            return
        elif grep -qi "^$title " "$bookmarksFile"; then
        yad --form --title="I38 - Bookmarks" --selectable-labels --field="A bookmark with the title \"$title\" already exists.":LBL --button="OK:0"
            return
        fi

        # Add the new bookmark
        echo "$title $url" >> "$bookmarksFile"

        # Ensure no duplicates with sort -u
        sort -u "$bookmarksFile" -o "$bookmarksFile"
        yad --form --title="I38 - Bookmarks" --selectable-labels --field="Bookmark \"$title\" added successfully.":LBL --button="OK:0"
        return
    done
}

# Prepare environment and read bookmarks
declare -a bookmarks
config="${XDG_CONFIG_HOME:-${HOME}/.config}"
if [[ -r "${config}/surfraw/bookmarks" ]]; then
    mapfile -t contents < "${config}/surfraw/bookmarks"
    for i in "${contents[@]}" ; do
        title="${i% *}"
        title="${title//_/ }"
        bookmarks+=("${title}")
        bookmarks+=("${i##* }")
    done
fi
if [[ -r "${config}/i3/bookmarks" ]]; then
    mapfile -t contents < "${config}/i3/bookmarks"
    for i in "${contents[@]}" ; do
        bookmarks+=("${i% *}" "${i##* }")
    done
fi

# Run yad to display the dialog
url=$(yad --list \
    --title="I38 - Bookmarks" \
    --text="Select a bookmark to open" \
    --column="Title" \
    --column="URL" \
    --button="Open Bookmark:0" \
    --button="Add Bookmark:1" \
    --button="Cancel:2" \
    --close-on-unfocus \
    --hide-column=2 \
    --search-column=1 \
    --skip-taskbar \
    "${bookmarks[@]}")
yadCode="$?"
url="${url%|*}"
url="${url##*|}"
case ${yadCode} in
    0) xdg-open "${url}";;
    1) add_bookmark;;
    2) exit 0;;
esac