#!/usr/bin/env python3

import argparse
import logging
import os
import scanner
from datetime import datetime
from scanner import downloader, dupecheck


def configure_logging(log_file: str, level=logging.INFO):
    logging.basicConfig(format='[%(asctime)s] -- %(levelname)s: %(message)s', datefmt='%Y%m%d-%H%M%S', filename=log_file, level=level)
    stdout_handler = logging.StreamHandler()
    stdout_handler.setFormatter(logging.Formatter(fmt='[%(asctime)s] -- %(levelname)s: %(message)s', datefmt='%Y%m%d-%H%M%S'))
    logging.getLogger().addHandler(stdout_handler)
    return logging.getLogger()


def condition_check(args:dict):
    """
    Build and returns a condition dict used by downloader.downloader to decide what picture to download.

    Args:
        args: program arguments parsed by argparse

    Returns:
        dict containing the conditions for download a picture
    """

    # Checking conditions
    condition = {}
    if args.extension:
        condition["ext"] = args.extension.split(',')
    else:
        condition["ext"] = False

    if args.filename:
        condition["filename"] = args.filename.split(',')
    else:
        condition["filename"] = False

    if args.width:
        condition["width"] = args.width
    else:
        condition["width"] = False

    if args.height:
        condition["height"] = args.height
    else:
        condition["height"] = False

    return condition


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('thread', help='url of the thread')
    parser.add_argument('folder', nargs='?',
                        help='Change the folder name where images are downloaded')
    parser.add_argument("-i", "--imageboard",
                        help="choose the imageboard you from to download from."
                        " Default to 4chan")
    parser.add_argument("-H", "--height",
                        help="Specify height. format: >256, <256 or =256")
    parser.add_argument("-W", "--width",
                        help="Specify width. format: >256, <256 or =256")
    parser.add_argument("-E", "--extension",
                        help="""Download only specific(s) extension(s). Ex: .jpg
                             (can be multiple extensions separated by ,)""")
    parser.add_argument("-f", "--filename",
                        help="""Download only images containing the string. Ex: filename_1
                             (can be multiple filenames separated by a ,)""")
    parser.add_argument("-d", "-disable-dupe-check", action='store_true',
                        help="with -d 4scanner will download images even if a duplicate exist in output folder.")
    parser.add_argument("-q", "--quiet", action='store_true', help="quiet")
    parser.add_argument("-s", "--single-run", action='store_true', help="Download all pictures and exit, do not wait for thread to 404")
    parser.add_argument("-t", "--tag", help="list of tags for importing easily into Hydrus Network, separated by ,")
    parser.add_argument("-o", "--output", help="Specify output folder")
    parser.add_argument("-T", "--throttle", help="Number of second to throttle between images download. Default: 2", nargs='?', default="2")
    args = parser.parse_args()

    thread_nb = str(args.thread.split('/')[5].split('.')[0])
    board = str(args.thread.split('/')[3])

    condition = condition_check(args)

    quiet = False
    if args.quiet:
        quiet = True

    if args.folder is not None:
        folder = ''.join(args.folder)
    else:
        folder = thread_nb

    if args.output is not None:
        output = args.output
        if not os.path.exists(output):
            print("{0} Does not exist.".format(output))
            exit(1)
    else:
        output = os.getcwd()

    if args.imageboard:
        chan = args.imageboard
    else:
        chan = "4chan"

    # Check if we download duplicate pictures
    if not args.d:
        dupe_check = True
    else:
        dupe_check = False

    if args.tag:
        tag = args.tag.split(',')
    else:
        tag = None

    # Setting up logger
    logger = configure_logging("./{}_4downloader.log".format(datetime.now().strftime('%Y%m%d_%H%M%S')))

    thread_downloader = downloader.downloader(thread_nb, board, chan, output, folder, quiet, condition, dupe_check, tag, args.throttle, logger, single_run=args.single_run)
    thread_downloader.download()


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
