from __future__ import print_function
import os
import sys
import re
from bs4 import BeautifulSoup
import urllib2

print(os.getcwd())

if len(sys.argv) > 1:
    path = sys.argv[1]
else:
    path="""http://myzuka.club/Album/99066/Drudkh-Slavonic-Chronicles-2010"""
mainLink = """http://myzuka.club"""

def linkOpener(url=path):
    url = url
    r = urllib2.Request(url=url)
    # r.add_header('Cookie', 'sessionid=13cxrt4uytfc6ijvgeoflmb3u9jmjuhil; csrftoken=jdEKPN8iL62hdaq1hmMuID9DMALiiDIq')
    r.add_header('Upgrade-Insecure-Requests', '1')
    #r.add_header('Accept-Encoding', 'gzip, deflate, sdch, br')
    r.add_header('User-Agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36')
    r.add_header('Connection', 'keep-alive')
    r.add_header('Cache-Control', 'max-age=0')
    r.add_header('Accept-Language', 'en-US,en;q=0.8,pt;q=0.6')
    r.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
    html = urllib2.urlopen(r)
    return html

bsObj = BeautifulSoup(linkOpener(path).read(), "lxml")
bodyContent = bsObj.find("div", {"id":"bodyContent"})
title = bsObj.h1.get_text().replace(" ", "_")
title = re.sub(ur'[^\x00-\x7F\x80-\xFF\u0100-\u017F\u0180-\u024F\u1E00-\u1EFF]', u'', title)
os.mkdir(title)
os.chdir(title)
linksList = bsObj.find_all("a",  {"href":re.compile("\/Song\/[A-Za-z0-9\-\/]+"), \
                                    "title":True})
print("List of songs created. Dir to save created")

for link in linksList:
    html = linkOpener("{}{}".format(mainLink, link["href"]))
    bsObj = bsObj = BeautifulSoup(html.read(), "lxml")
    listToDownload = bsObj.find_all("a", {"href":re.compile("\/Song\/Download\/"), "itemprop":"audio"})
    if len(listToDownload) != 1:
        print("Something went wrong! Download page has {} link to download".format(len(listToDownload)))
    response = linkOpener("{}{}".format(mainLink, listToDownload[0]["href"])).read()

    filename = bsObj.find("h1").get_text()
    file_ = open(filename, 'w')
    file_.write(response)
    file_.close()
    print("File downloaded")
