#!/usr/bin/env python3

import openaccess_epub as oae
import openaccess_epub.utils as utils
import os.path
import logging
import shutil

CACHE_LOCATION = utils.cache_location()

#Import the global config file as a module
import imp
config_path = os.path.join(CACHE_LOCATION, 'config.py')
try:
    config = imp.load_source('config', config_path)
except IOError:
    print('Could not find {0}, please run oae-quickstart'.format(config_path))
    sys.exit()

def main():
    """The main method of the launch script"""
    args = oae.OAEParser()
    #Configure logging, 
    if args.input:
        #Get the name of the article xml file, replacing .xml with .log
        if 'http:' in args.input:
            log_name = utils.url_input(args.input, download=False) + '.log'
        elif 'doi:' in args.input:
            log_name = utils.doi_input(args.input, download=False) + '.log'
        else:
            log_name = os.path.splitext(os.path.basename(args.input))[0] + '.log'
    elif args.batch:
        log_name = os.path.split(utils.get_absolute_path(args.batch))[1] + '.log'
    elif args.parallel_batch:
        log_name = os.path.split(utils.get_absolute_path(args.parallel_batch))[1] + '.log'
    elif args.zip:
        log_name = os.path.split(utils.get_absolute_path(args.batch))[0] + '.log'
        logname = os.path.splitext(os.path.basename(args.zip))[0] + '.log'
    elif args.collection:
        log_name = os.path.split(os.getcwd())[1] + '_collection.log'
    
    output_dir = utils.get_output_directory(args)
    log_path = os.path.join(output_dir, log_name)
    if not os.path.isdir(output_dir):
        utils.mkdir_p(output_dir)
    logging.basicConfig(filename=log_path, level=logging.DEBUG)
    logging.info('openaccess_epub Log v.{0}'.format(oae.__version__))
    #Run the main script
    oae.main(args)


if __name__ == '__main__':
    main()
