#!/usr/bin/env python 
import argparse
import ctypes
import os
import platform
import shutil
import sys
import time

import praw
import requests
from PIL import Image

try:
    import pwd
except:
    pass

def sanitize(link):
    if 'jpg' in link or 'png' in link:
        return link
    elif 'imgur' in link:
        return link + '.png'
    else:
        raise ValueError('cant sanitize url' + link)

def get_username():
    return pwd.getpwuid( os.getuid() )[ 0 ]


def linux_wallpaper(path):
    de = os.environ.get('DESKTOP_SESSION')
    if de in ["gnome", "unity", "ubuntu"]:
        os.system("gsettings set org.gnome.desktop.background picture-uri file://%s" % path)
    elif de in ["cinnamon"]:
        os.system("gsettings set org.cinnamon.desktop.background picture-uri file://%s" % path)
    elif de in ["mate"]:
        os.system("gsettings set org.mate.background picture-filename '%s'" % path)
    elif de in ['xfce']:
        os.system("xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-show -s ''")
        os.system("xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-path -s '%s'" % path)
    else:
        print("Your DE could not be detected to set the wallpaper.")
        sys.exit(1)

def main():
    description = "Set trending reddit images as wallpapers"
    parser = argparse.ArgumentParser(description = description)

    parser.add_argument("-sr", "--sub-reddit", default="EarthPorn",type=str, nargs='+',
        help="Sub reddit name, eg earthporn")
    parser.add_argument("-sort", "--sort-method", default="get_top_from_all", type=str, nargs='+',
        help="Sort method , eg: get_hot")
    parser.add_argument("-t", "--time", type=int, default=5, nargs='+',
                        help="Time (in seconds) duration for each wallpaper")
    parser.add_argument("-count", "--count", type=int, default=10, nargs='+',
                        help="Count of total number of wallpapers to select")
    args = parser.parse_args()

    if platform.system() == 'Darwin' or platform.system() == 'Linux':
        r = praw.Reddit(user_agent='RedditWallpaper Script by ' + get_username())
    else:
        r = praw.Reddit(user_agent='RedditWallpaper Script by /r/somewindowsuser')


    sub_reddit = args.sub_reddit
    sort_method = args.sort_method
    wall_duration = args.time
    count = args.count
    if isinstance(sub_reddit, list):
        sub_reddit = sub_reddit[0]
        sort_method = sort_method[0]
        wall_duration = wall_duration[0]
        count = count[0]

    print sub_reddit, sort_method, wall_duration, count
    submissions = getattr(r.get_subreddit(str(sub_reddit)), str(sort_method))(limit= count)


    my_dir = os.path.expanduser('~/.epwallpapers')

    # Create .epwallpapers directory to store all images
    if not os.path.exists(my_dir):
        os.makedirs(my_dir)

    i = 0
    wlinks = []
    for each in submissions:
        wlinks.append(each)
    wcounts = len(wlinks)

    while True:
        fail = False
        print i
        each = wlinks[i]
        try:
            url = sanitize(each.url)
            imgext = url.split('.')[-1]
        except ValueError as e:
            print e
            i+=1
            continue

        response = requests.get(url, stream=True)

        # Download images in  ~/.epwallpapers directory all images
        with open(my_dir + '/' + str(i) + '.' + imgext, 'wb') as out_file:
            shutil.copyfileobj(response.raw, out_file)

        imagePath = my_dir + '/' + str(i) + '.' + imgext

        with Image.open(imagePath) as im:
            width, height = im.size
            # We only want high resolution images
            if int(width) < 2000 or int(height) < 1300:
                i+=1
                print 'poor pic, failed'
                fail = True

        if fail:
            continue
        if platform.system() == 'Darwin':
            # osxcmd = 'osascript -e \'tell application "Finder" to set desktop picture to POSIX file "' + imagePath + '" \''
            osxcmd = 'osascript -e \'tell application "System Events" to set picture of every desktop to "' + imagePath + '" \''

            os.system(osxcmd)
        elif platform.system() == 'Windows':
            SPI_SETDESKWALLPAPER = 20
            ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, imagePath, 3)
        elif platform.system() == 'Linux':
            linux_wallpaper(imagePath)
        else:
            print 'Platform not recognized'
            sys.exit()
        print 'Done'

        i += 1
        if i == wcounts -1:
            i = 0
        time.sleep(wall_duration * 60)


if __name__ == '__main__':
    main()
