__author__ = "Vishvendra Singh"
__version__ = 0.1


import cPickle as pickle
from bs4 import BeautifulSoup
import requests
import os
import time

# global constants
CONFIG_FILE = ".img_dl_links.p"
DOWNLOAD_PATH = ".dl_path.txt"
BASE_URL = "http://simpledesktops.com"


def image_links_from_page(htmlsource):
    """returns images links and address of next page"""
    img_links = []
    soup = BeautifulSoup(htmlsource)
    div_src = soup.find_all("div", {"class": "desktop"})
    for each_div in div_src:
        soup2 = BeautifulSoup(str(each_div))
        img_links.append(soup2.find("img")["src"])

    img_links = extract_img_url(img_links)

    next_link = soup.find("a", {"class": "more"})
    if next_link:
        return img_links, next_link["href"]
    else:
        return img_links, None


def extract_img_url(img_links):
    tmp = []
    for each_link in img_links:
        if "jpg" in each_link:
            tmp.append(each_link[0:each_link.find("jpg") + 3])
        elif "png" in each_link:
            tmp.append(each_link[0: each_link.find("png") + 3])
    return tmp


def file_exist_status(file_name):
    """check existence of a file. used for checking status of config file"""
    if os.path.isfile(file_name) and os.access(file_name, os.R_OK):
        return True
    else:
        return False


def get_all_image_links():
    """retrieves all image links of images available on simpledesktops.com"""
    img_dl_links = []
    next_link = "/browse/1/"
    while next_link:
        fh = requests.get("%s%s" % (BASE_URL, next_link), allow_redirects=False)
        print fh.url
        result = image_links_from_page(fh.text)
        fh.close()
        img_dl_links.append(result[0])
        next_link = result[1]
        print next_link
    # flattening list of links
    tmp = []
    for x in img_dl_links:
        for y in x:
            tmp.append(y)
    img_dl_links = tmp
    return img_dl_links


def get_dl_path():
    print "input path to save files:",
    PATH = raw_input()
    if os.path.isdir(PATH) and os.access(PATH, os.W_OK):
        print "given path accepted"
        return PATH
    else:
        print "path is not valid"
        get_dl_path()


def download_images(img_dl_links, PATH):
    """download images and remove downloaded images from img_links"""
    for img_url in img_dl_links:
        tmp = requests.request('get', img_url)
        with open(os.path.join(PATH, img_url.split('/')[-1]), 'w') as f:
            f.write(tmp.content)
        update_config_file(img_url)
        time.sleep(1)


def update_config_file(img_link):
    """remove downloaded links from config file"""
    img_dl_links = pickle.load(open(CONFIG_FILE, "rb"))
    img_dl_links.pop(img_dl_links.index(img_link))
    pickle.dump(img_dl_links, open(CONFIG_FILE, "wb"))


def main():
    if file_exist_status(CONFIG_FILE) and file_exist_status(DOWNLOAD_PATH):
        img_dl_links = pickle.load(open(CONFIG_FILE, "rb"))
        PATH = ""
        with open(DOWNLOAD_PATH) as f:
            PATH = f.read()
        print "downloading wallpapers be patience..."
        print "to terminate/stop script press Ctrl+z"
        download_images(img_dl_links, PATH)
        print "wallpapers download complete"
    else:
        PATH = get_dl_path()
        with open(DOWNLOAD_PATH, "w") as f:
            f.write(PATH)
        img_dl_links = get_all_image_links()
        pickle.dump(img_dl_links, open(CONFIG_FILE, "wb"))
        print "downloading wallpapers be patience..."
        print "to terminate/stop script press Ctrl+z"
        download_images(img_dl_links, PATH)
        print "wallpapers download complete"


if __name__ == "__main__":
    main()

@@ -100,16 +100,35 @@
 fulSoup%0A
+import progressbar%0A
 import r
@@ -135,16 +135,16 @@
 equests%0A
-
 import o
@@ -1432,24 +1432,155 @@
 tops.com%22%22%22%0A
+    pbar = progressbar.AnimatedProgressBar(end=47, width=50)%0A    print %22getting all links for image urls%22%0A    pbar.show_progress()%0A
     img_dl_l
@@ -1723,24 +1723,26 @@
 lse)%0A       
+ #
  print fh.ur
@@ -1882,24 +1882,73 @@
 t%5B1%5D%0A       
+ pbar += 1%0A        pbar.show_progress()%0A        #
  print next_
@@ -1983,16 +1983,27 @@
 f links%0A
+    print %0A
     tmp 
@@ -2498,24 +2498,176 @@
 mg_links%22%22%22%0A
+    end = len(img_dl_links)%0A    pbar = progressbar.AnimatedProgressBar(end=end, width=50)%0A    print 'downloading wallpapers..'%0A    pbar.show_progress()%0A
     for img_
@@ -2898,16 +2898,75 @@
 leep(1)%0A
+        pbar += 1%0A        pbar.show_progress()%0A    print %0A%0A
 %0A%0Adef up
@@ -3452,32 +3452,30 @@
      print %22
-download
+%5Bresum
 ing wallpape
@@ -3475,32 +3475,26 @@
 allpaper
-s be patience...
+ download%5D
 %22%0A      
@@ -3506,32 +3506,28 @@
 nt %22
+%5B
 to 
-terminate/stop script
+stop downloading
  pre
@@ -3527,32 +3527,33 @@
 ing press Ctrl+z
+%5D
 %22%0A        downlo
@@ -3855,16 +3855,25 @@
  print %22
+%5Bto stop 
 download
@@ -3880,75 +3880,8 @@
 ing 
-wallpapers be patience...%22%0A        print %22to terminate/stop script 
 pres
@@ -3888,16 +3888,17 @@
 s Ctrl+z
+%5D
 %22%0A      

add progressbar