#!/usr/bin/python3
import subprocess
import json
import os
import random
import PIL
from PIL import Image
import argparse

# Parse arguments for device
parser = argparse.ArgumentParser(description="Path")
parser.add_argument('text', action='store', type=str, help='Path to wallpapers')
args = parser.parse_args()

# Path to wallpapers
wall_path = os.path.expanduser(args.text)

# Create list of wallpapers
walls = {}
for filename in os.listdir(wall_path):
    f = os.path.join(wall_path, filename)
    # checking if it is a file
    if os.path.isfile(f):
        # Load image as pillow object
        img = PIL.Image.open(f)
        # Get the dimensions of the image
        x, y = img.size
        walls[f] = {"x": x, "y": y}

# Get the display info
outputs = json.loads(
    subprocess.run(["swaymsg", "-t", "get_outputs"], capture_output=True).stdout.decode('utf=8')
)

used = []
# Set random wallpaper for display
for output in outputs:
    # Check if display is landscape or portrait
    if output["rect"]["width"] > output["rect"]["height"]:
        landscape = True
    else:
        landscape = False

    # Generate list of valid walls to pick from
    valid = []
    for wall, dimensions in walls.items():
        # Only use wallpaper if the resolution is greater than or equal to the display resolution
        if dimensions["x"] >= output["rect"]["width"] and dimensions["y"] >= output["rect"]["height"]:
            # Only use the wallpaper if its orientation matches the display
            if (dimensions["x"] > dimensions["y"]) == landscape:
                valid.append(wall)

    # Remove used wallpapers from valid list to avoid picking them
    for wall in used:
        try:
            valid.remove(wall)
        # Ignore value errors since the valid list won't be the same for every monitor
        except ValueError:
            pass

    # Pick a random wallpaper and add it to the used list
    wall = random.choice(valid)
    used.append(wall)

    # Set the wallpaper
    subprocess.run(["swaymsg", "output", output["name"], "bg", wall, "fill"])
