import logging
import sys
import os
import logging.handlers


from argparse import ArgumentParser
from datetime import datetime as dt


class ArcPyLogHandler(logging.StreamHandler):
    """
    Custom logging class that bounces messages to the arcpy tool window as well
    as reflecting back to the file.
    """

    def emit(self, record):
        """
        Write the log message
        """
        try:
            msg = record.msg.format(record.args)
        except Exception as e:
            msg = record.msg

        if record.levelno == logging.ERROR:
            arcpy.AddError(msg)
        elif record.levelno == logging.WARNING:
            arcpy.AddWarning(msg)
        elif record.levelno == logging.INFO:
            arcpy.AddMessage(msg)
        else:
            arcpy.AddMessage(msg)

        super(ArcPyLogHandler, self).emit(record)


###############################################################################
# helper (manipulates handlers for the logic of the application)

def run_app():
    """Run the logic of application"""
    gdb, logger = get_input_parameter()
    reset_database(gdb, logger)


def get_input_parameter():
    """
    Parse arguments and set up logger

    :return: directory where "Data Loading Directory" will be created, version of TEIS data load process
    :rtype: str, str
    """
    try:
        parser = ArgumentParser(
            description='Run this script to reset the Stage_1 geodatabase')
        parser.add_argument('gdb', help='Path to the Stage_1 geodatabase within the contractor package.')
        parser.add_argument('--log_level', default='INFO', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'],
                            help='Log level')
        parser.add_argument('--log_dir', help='Path to log Directory')
        args = parser.parse_args()

        log_name = 'main_logger'
        logger = logging.getLogger(log_name)
        logger.handlers = []

        log_fmt = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        log_file_base_name = os.path.basename(sys.argv[0])
        log_file_extension = 'log'
        timestamp = dt.now().strftime('%Y-%m-%d_%H-%M-%S')
        log_file = "{}_{}.{}".format(timestamp, log_file_base_name, log_file_extension)

        logger.setLevel(args.log_level)

        sh = logging.StreamHandler()
        sh.setLevel(args.log_level)
        sh.setFormatter(log_fmt)
        logger.addHandler(sh)

        args.log_dir = os.path.join(os.path.dirname(sys.argv[0]), 'log')
        if args.log_dir:
            try:
                os.makedirs(args.log_dir)
            except OSError:
                pass

            fh = logging.FileHandler(os.path.join(args.log_dir, log_file))
            fh.setLevel(args.log_level)
            fh.setFormatter(log_fmt)
            logger.addHandler(fh)

            if args.gdb:
                loading_log_file = os.path.join(os.path.dirname(args.gdb), 'Loading_Log.log')
                if os.path.exists(loading_log_file):
                    os.remove(loading_log_file)
                fh2 = logging.FileHandler(loading_log_file)
                fh2.setLevel(args.log_level)
                fh2.setFormatter(log_fmt)
                logger.addHandler(fh2)

        if os.path.basename(sys.executable).lower() == 'python.exe':
            arc_env = False
        else:
            arc_env = True

        if arc_env:
            arc_handler = ArcPyLogHandler()
            arc_handler.setLevel(args.log_level)
            arc_handler.setFormatter(log_fmt)
            logger.addHandler(arc_handler)

        # Start the script
        return args.gdb, logger

    except Exception as e:
        logging.exception('Unexpected exception. Program terminating.')
        exit(1)


def reset_database(gdb, logger):
    logger.info("Clearing the Stage_1.gdb database")
    arcpy.env.workspace = gdb
    tables = arcpy.ListTables()
    fields = arcpy.ListFeatureClasses()
    for field in fields:
        logger.info("Removing table {}".format(field))
        arcpy.DeleteRows_management(field)

    for table in tables:
        logger.info("Removing table {}".format(table))
        arcpy.DeleteRows_management(table)
    logging.info("Cleared the Stage_1.gdb database")


if __name__ == '__main__':
    try:
        # Import arcpy
        import arcpy
    except Exception as e:
        logging.error('No ArcGIS licenses available to run this tool.  Program terminating.')
        sys.exit(1)
    run_app()
else:
    try:
        # Import arcpy
        import arcpy
    except Exception as e:
        logging.error('No ArcGIS licenses available to run this tool.  Program terminating.')
        sys.exit(1)
