#!/bin/bash

SCRIPTS_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
source $SCRIPTS_DIR/config.sh

#####################################
###   Needed for NSFW/Favorites   ###
#####################################
# Enter your API key
# you can get it here: https://wallhaven.cc/settings/account
APIKEY=""
#####################################
### End needed for NSFW/Favorites ###
#####################################

#####################################
###     Configuration Options     ###
#####################################
# Where should the Wallpapers be stored?


LOCATION=$WALLPAPER_DIR

SEARCH=""
# What page to start downloading at, default and minimum of 1.
STARTPAGE=1
# Type standard (newest, oldest, random, hits, mostfav), search, collections
# (for now only the default collection), useruploads (if selected, only
# FILTER variable will change the outcome)
TYPE=single
# From which Categories should Wallpapers be downloaded, first number is
# for General, second for Anime, third for People, 1 to enable category,
# 0 to disable it
CATEGORIES=100
# filter wallpapers before downloading, first number is for sfw content,
# second for sketchy content, third for nsfw content, 1 to enable,
# 0 to disable
FILTER=100
# Which Resolutions should be downloaded, leave empty for all (most common
# resolutions possible, for details see wallhaven site), separate multiple
# resolutions with , eg. 1920x1080,1920x1200
RESOLUTION=
# alternatively specify a minimum resolution, please note that specifying
# both resolutions and a minimum resolution will result in the desired
# resolutions being ignored, to avoid unwanted behavior only set one of the
# two options and leave the other blank
ATLEAST=2560x1440
# Which aspectratios should be downloaded, leave empty for all (possible
# values: 4x3, 5x4, 16x9, 16x10, 21x9, 32x9, 48x9, 9x16, 10x16), separate mutliple ratios
# with , eg. 4x3,16x9
ASPECTRATIO=16x9,16x10
# Which Type should be displayed (relevance, random, date_added, views,
# favorites, toplist, toplist-beta)
MODE=random
# if MODE is set to toplist show the toplist for the given timeframe
# possible values: 1d (last day), 3d (last 3 days), 1w (last week),
# 1M (last month), 3M (last 3 months), 6M (last 6 months), 1y (last year)
TOPRANGE=1M
# How should the wallpapers be ordered (desc, asc)
ORDER=desc
# Collections, only used if TYPE = collections
# specify the name of the collection you want to download
# Default is the default collection name on wallhaven
# If you want to download your own Collections make sure USR is set to your username
# If you want to download someone elses public collection enter the name here
# and the username under USR
# Please note that the only filter option applied to Collections is the Number
# of Wallpapers to download, there is no filter for resolution, purity, ...
COLLECTION="Default"
# Searchterm, only used if TYPE = search
# you can also search by tags, use id:TAGID
# to get the tag id take a look at: https://wallhaven.cc/tags/
# for example: to search for nature related wallpapers via the nature tag
# instead of the keyword use QUERY="id:37"
QUERY="nature"
# Search images containing color
# values are RGB (000000 = black, ffffff = white, ff0000 = red, ...)
COLOR=""
# Should the search results be saved to a separate subfolder?
# 0 for no separate folder, 1 for separate subfolder
SUBFOLDER=0
# User from which wallpapers should be downloaded
# used for TYPE=useruploads and TYPE=collections
# If you want to download your own Collection this has to be set to your username
USR=
# use gnu parallel to speed up the download (0, 1), if set to 1 make sure
# you have gnuparallel installed, see normal.vs.parallel.txt for
# speed improvements
# using this option can lead to cloudflare blocking some of the downloads
PARALLEL=0
# custom thumbnails per page
# changeable here: https://wallhaven.cc/settings/browsing
# valid values: 24, 32, 64
# if set to 32 or 64 you need to provide an api key
THUMBS=24
#####################################
###   End Configuration Options   ###
#####################################
# downloads Page with Thumbnails


s1="search?q=$SEARCH&categories=$CATEGORIES&purity=$FILTER&"
s1+="atleast=$ATLEAST&resolutions=$RESOLUTION&ratios=$ASPECTRATIO"
s1+="&sorting=$MODE&order=$ORDER&topRange=$TOPRANGE&colors=$COLOR"

# API URL for searching wallpapers
API_URL="https://wallhaven.cc/api/v1/$s1"

# Fetch the JSON response
response=$(curl -s "$API_URL")

# Extract the first wallpaper ID from the JSON response
wallpaper_id=$(echo "$response" | jq -r '.data[0].id')

# Check if an ID was found
if [ -z "$wallpaper_id" ]; then
    echo "No wallpaper ID found."
    exit 1
fi

# Construct the wallpaper API URL
WALLPAPER_URL="https://wallhaven.cc/api/v1/w/$wallpaper_id"

#printf "Download Page %s\\n" "$WALLPAPER_URL"

# Fetch wallpaper details
wallpaper_details=$(curl -s "$WALLPAPER_URL")

# Extract the image URL
image_url=$(echo "$wallpaper_details" | jq -r '.data.path')
image_type=$(echo "$wallpaper_details" | jq -r '.data.type')
#echo "$wallpaper_details"

# Check if an image URL was found
if [ -z "$image_url" ]; then
    echo "No image URL found."
    exit 1
fi

# Get the file extension from the URL
file_extension="${image_url##*.}"

#echo "File Type is $file_extension"

# Ensure extension is valid
if [[ ! "$file_extension" =~ ^(jpg|jpeg|png|webp)$ ]]; then
    echo "Unknown or unsupported file extension: $file_extension"
    exit 1
fi

# Download the wallpaper
#echo "Downloading wallpaper: $image_url"

wget -q "$image_url" -O "$LOCATION/$wallpaper_id.$file_extension"
notify-send "Wallpaper Download :" "Downloaded from : $image_url \n to : $WALLPAPER_DIR" --icon=dialog-information -t 3000

echo "${wallpaper_id}"
