from os import getcwd, makedirs
from os.path import basename, join, splitext
from time import sleep
from urllib import urlopen, urlretrieve
from urlparse import urlparse

import json

'''
You can use the following code to download the manga list, but it's too slow:

url = 'https://www.mangaeden.com/api/list/0/'
response = urlopen(url)
mangasData = json.loads(response.read())
'''
mangasData = json.loads(open('mangasData.json').read())
aliasToDownload = 'zipang'
cwd = getcwd()

for k, v in mangasData.iteritems():
    if k == 'manga':
        mangas = v

        for manga in mangas:
            alias = manga['a']

            if alias == aliasToDownload:
                id = manga['i']
                dataUrl = 'https://www.mangaeden.com/api/manga/' + id + '/'
                data = json.loads(urlopen(dataUrl).read())
                chapters = data['chapters']

                chapters.reverse()

                for chapter in chapters:
                    chapterNumber = chapter[0]
                    chapterId = chapter[3]
                    chapterUrl = 'https://www.mangaeden.com/api/chapter/' + chapterId + '/'
                    chapterData = json.loads(urlopen(chapterUrl).read())
                    chapterImages = chapterData['images']
                    chapterPath = join(cwd, aliasToDownload.capitalize(), str(chapterNumber).zfill(2))

                    makedirs(chapterPath)
                    chapterImages.reverse()

                    i = 0

                    for chapterImage in chapterImages:
                        chapterImageUrl = 'http://cdn.mangaeden.com/mangasimg/' + chapterImage[1]
                        fileName, fileExtension = splitext(basename(urlparse(chapterImageUrl).path))
                        chapterImagePath = join(chapterPath, str(i + 1).zfill(2) + fileExtension)

                        urlretrieve(chapterImageUrl, chapterImagePath)

                        i += 1

                    sleep(60)

                break
