#!/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('path', action='store', type=str, help='Path to wallpapers')
args = parser.parse_args()

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

# 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:
    wall, dimensions = random.choice(list(walls.items()))
    del walls[wall]
    
    if dimensions["x"] >= output["rect"]["width"]/2 and dimensions["y"] >= output["rect"]["height"]/2:
        subprocess.run(["swaymsg", "output", output["name"], "bg", wall, "fill"])
    else:
        subprocess.run(["swaymsg", "output", output["name"], "bg", wall, "center", "#1c1f26"])
