#!/usr/bin/env python3
import os
import subprocess
from datetime import datetime, timedelta
from PIL import Image

import imagehash
import requests


today = datetime.today().strftime("%Y-%m-%d")
yesterday = (datetime.today() - timedelta(days=1)).strftime("%Y-%m-%d")
home = os.path.expanduser("~")
check_path = f"{home}/var/media/backgrounds/bing/{yesterday}.jpg"
target_path = f"{home}/var/media/backgrounds/bing/{today}.jpg"

# If the file for today already exists, just exit
if os.path.isfile(target_path):

    found_match = False
    try:
        yesterday_img = imagehash.average_hash(Image.open(check_path))
        today_img = imagehash.average_hash(Image.open(target_path))
        cutoff = 5  # maximum bits that could be different between the hashes. 

        found_match = today_img - yesterday_img < cutoff
    except:
        pass

    if not found_match:
        print(f"Bing image for {today} already exists, skipping download")
        exit()

    print(f"Bing image for {today} same as yesterday, overwriting")

iotd_uri = "https://www.bing.com/HPImageArchive.aspx?format=js&idx=1&n=1"
r = requests.get(iotd_uri)
image_info_uri = r.json()["images"][0]["url"]
img = requests.get(f"https://www.bing.com{image_info_uri}", stream=True)

handle = open(target_path, "wb")
for chunk in img.iter_content(chunk_size=512):
    if chunk:  # filter out keep-alive new chunks
        handle.write(chunk)
