#!/usr/bin/env python3

"""Set the wallpaper.

---
source: https://github.com/dylanaraps/pywal
"""

import os
import subprocess
import sys


# from pywal
def set_mac_wallpaper(img):
    """Set the wallpaper on macOS."""
    db_path = os.environ["HOME"] + "/Library/Application Support/Dock/desktoppicture.db"

    # put the image path in the database
    sql = "insert into data values(\"%s\"); " % img
    subprocess.call(["sqlite3", db_path, sql])

    # get the index of the new entry
    sql = "select max(rowid) from data;"
    new_entry = subprocess.check_output(["sqlite3", db_path, sql])
    new_entry = new_entry.decode('utf8').strip('\n')

    # get all picture ids (monitor/space pairs)
    get_pics_cmd = ['sqlite3', db_path, "select rowid from pictures;"]
    pictures = subprocess.check_output(get_pics_cmd)
    pictures = pictures.decode('utf8').split('\n')

    # clear all existing preferences
    sql += "delete from preferences; "

    # write all pictures to the new image
    for pic in pictures:
        if pic:
            sql += 'insert into preferences (key, data_id, picture_id) '
            sql += 'values(1, %s, %s); ' % (new_entry, pic)

    subprocess.call(["sqlite3", db_path, sql])

    # kill the dock to fix issues with cached wallpapers
    # macOS caches wallpapers and if a wallpaper is set that shares
    # the filename with a cached wallpaper, the cached wallpaper is
    # used instead
    subprocess.call(["killall", "Dock"])

set_mac_wallpaper(sys.argv[1])
