#!/usr/bin/env python
# -*- coding:utf-8 -*-

'''Copyright (c) 2016, Ryo Hanafusa.
All rights reserved.'''

import os
import sys
import time

try:
    MY_MODUDLES = [
        'ablog_scrape-2.0',
        'urldl-2.3',
        'colpri-2.3',
        'fileope-1.0'
        ]

    for mod in MY_MODUDLES:
        sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/' + mod)

    from fileope import FileOperation
    from ablogscrape import AblogScrape
    from urldl import URLDownload
    from colpri import ColorPrint
except:
    print 'Could not load some modules'
    sys.exit(1)
finally:
    pass

# Global variable
TIME_SLEEP = 1.0


def main():
    '''main'''
    absc = AblogScrape()
    c_p = ColorPrint()
    dler = URLDownload()
    stg = FileOperation()

    print c_p.with_color('A Blog Scraping', 'purple')
    print c_p.with_color('Checking the savepath', 'cyan')
    dler.load_savepath()

    print c_p.with_color('Checking the latest article', 'cyan')
    stg.load_file('LATEST_ARTICLE.txt')

    latest_article = stg.readline()
    absc.set_latest_article(latest_article)
    scraper = absc.main_scrape()

    image_number = 0

    while True:
        try:
            print '-' * 50
            image_urls = scraper.next()
            for image in image_urls:
                print image
            print

            image_urls.reverse()
            for image in image_urls:
                image_number += 1
                c_p.with_color(['Image No.', str(image_number)], 'purple')
                dler.download(image)
                time.sleep(TIME_SLEEP)
        except StopIteration:
            print '*** Scaping finish ***'
            break
        finally:
            pass

    new_latest_article = absc.get_new_latest_article()
    stg.update_content(new_latest_article)

    c_p.with_color(['Downloaded', str(image_number), 'images'], 'purple')

if __name__ == '__main__':
    main()
