import tempfile
import time
import argparse
from os import path

from flask import Flask

from memento_damage import utils
from web.database import db

flaskApp = None


def parseArgs():
    # Handle command-line arguments
    parser = argparse.ArgumentParser(
        prog='Memento Damage CLI',
        description='CLI utility for analysis of Mementos and web pages',
        usage='%(prog)s [options] <URI>',
        epilog='oduwsdl.github.io @WS-DL')
    parser.add_argument('-c', '--cache-dir', required=True,
                        dest='CACHE_DIR',
                        help='Set specified cache path')
    parser.add_argument('-d', '--debug',
                        dest='DEBUG', action='store_true',
                        help='Enable debugging mode (default: off)')
    parser.add_argument('-i', '--ignore-cache',
                        dest='IGNORE_CACHE', action='store_true',
                        help='Ignore and overwrite existing cache data (default: off)')
    # parser.add_argument('-m', '--mode',
    #                     dest='MODE',
    #                     choices=['analytic', 'visual'], default='analytic',
    #                     help='Sets analysis mode {analytic|visual} (default: analytic)')
    # parser.add_argument('-o', '--output-type',
    #                     dest='OUTPUT_TYPE',
    #                     choices=['txt', 'json'], default='txt',
    #                     help='Sets output type {txt|json} (default: txt)')
    # parser.add_argument('-q', '--quiet',
    #                     dest='QUIET', action='store_true',
    #                     help='Suppress logging to console')
    parser.add_argument('-r', '--redirect',
                        dest='REDIRECT', action='store_true',
                        help='Follow URI redirections')
    parser.add_argument('-t', '--timeout',
                        dest='TIMEOUT',
                        type=int, choices=range(10, 180), default=30,
                        help='Crawl timeout (in seconds)')
    parser.add_argument('-V', '--verbose',
                        dest='VERBOSE', action='store_true',
                        help='Enable extended logging output')
    parser.add_argument('-v', '--version',
                        action='version',
                        version='%(prog)s v3.0.0',
                        help='Display version information')
    parser.add_argument('-w', '--warc',
                        dest='WARC',
                        help='WARC/WACZ URI or file path from WARC_DIR')
    parser.add_argument('-W', '--warc-dir',
                        dest='WARC_DIR',
                        help='Local file path containing WARC/WACZ files')
    parser.add_argument('URI',
                        help='URI to analyze')
    args = parser.parse_args()

    if len(sys.argv) < 1:
        parser.print_help()
        exit(1)

    return args





def main():
    parser = argparse.ArgumentParser(
        prog='Memento Damage web server',
        description="Web service for ODU WS-DL's Memento Damage utility",
        usage='%(prog)s [options]',
        epilog='oduwsdl.github.io @WS-DL'
    )
    parser.add_argument("-d", "--debug",
                      action="store_true", dest="DEBUG", default=False,
                      help="Enable server debug mode")
    parser.add_argument("-H", "--host",
                      dest="HOST", default='0.0.0.0',
                      help="Server hostname or IP address")
    parser.add_argument("-o", "--output-dir",
                      dest="CACHE_DIR", default=None,
                      help="Set specific output directory (optional)")
    parser.add_argument("-P", "--port",
                      dest="PORT", default=8080,
                      help="Specify port number (default: 8080)")
    parser.add_argument('-V', '--version',
                        action='version',
                        version='%(prog)s 3.0.0',
                        help='Display version information')
    args = parser.parse_args()
    options = vars(args)

    # Handle output-dir flag
    if args.CACHE_DIR:
        if not path.isabs(args.CACHE_DIR):
            options['CACHE_DIR'] = path.abspath(path.join(utils.projectRoot(), args.CACHE_DIR))
        else:
            cacheDir = args.CACHE_DIR
        utils.mkDir(cacheDir)
        options['CLEAN_CACHE'] = False
    else:
        options['CACHE_DIR'] = tempfile.mkdtemp()
        options['CLEAN_CACHE'] = True

    # Add some necessary config variables
    options['BASE_URL']                         = f'http://{args.HOST}:{args.PORT}'
    options['BASE_DIR']                         = path.abspath(path.join(path.dirname(__file__)))
    options['TEMPLATE_DIR']                     = path.join(options['BASE_DIR'], 'templates')
    options['SQLALCHEMY_DATABASE_URI']          = 'sqlite:///' + path.join(options['CACHE_DIR'], 'app.db')
    options['SQLALCHEMY_TRACK_MODIFICATIONS']   = False
    options['DATABASE_CONNECT_OPTIONS']         = {}
    options['THREADS_PER_PAGE']                 = 10
    options['CSRF_ENABLED']                     = True
    options['CSRF_SESSION_KEY']                 = 'secret'
    options['SECRET_KEY']                       = 'secret'
    options['EXPLAIN_TEMPLATE_LOADING']         = True


    flaskApp = Flask(__name__, instance_relative_config=True)
    flaskApp.config.from_mapping(options)

    db.init_app(flaskApp)


    print(flaskApp.config['BASE_DIR'])
    print(flaskApp.config['TEMPLATE_DIR'])


    with flaskApp.app_context():
        from .pages.home import home_bp
        from .pages.help import help_bp
        from .pages.contact import contact_bp
        from .pages.faq import faq_bp
        from .pages.api import api_bp

        print(home_bp.template_folder)


        flaskApp.register_blueprint(help_bp)
        flaskApp.register_blueprint(faq_bp)
        flaskApp.register_blueprint(contact_bp)
        flaskApp.register_blueprint(api_bp)
        flaskApp.register_blueprint(home_bp)

        db.create_all()

    flaskApp.run(host=options['HOST'], port=options['PORT'], debug=options['DEBUG'], threaded=True, use_reloader=False)
    # If CLEAN_CACHE set to True, clean cache directory after server is closed
    if options['CLEAN_CACHE']:
        time.sleep(3)
        utils.rmdir_recursive(options['CACHE_DIR'], exception_files=[r'app.db'])



def startApiServer():
    pass


def startPresentationServer():
    pass