#!/usr/bin/env python3

import logging
import argparse
import dryable
import time
from qcrepocleaner.Ccdb import Ccdb
import sys

def parseArgs():
    """Parse the arguments passed to the script."""
    logging.info("Parsing arguments")
    parser = argparse.ArgumentParser(description='Remove all the objects in a given time interval in a given path')
    parser.add_argument('--url', dest='url', action='store', help='URL of the CCDB, with http[s]://', required=True)
    parser.add_argument('--log-level', dest='log_level', action='store', default="20",
                        help='Log level (CRITICAL->50, ERROR->40, WARNING->30, INFO->20,DEBUG->10)')
    parser.add_argument('--dry-run', action='store_true',
                        help='Dry run, no actual deletion nor modification to the CCDB.')
    parser.add_argument('--path', dest='path', action='store', default="",
                        help='Clean this path (without initial slash and without .* at the end, e.g. qc/TST/MO/Bob).', required=True)
    parser.add_argument('--from', dest='from_ts', action='store', help='From this timestamp.', required=True)
    parser.add_argument('--to', dest='to_ts', action='store', help='To this timestamp.', required=True)
    parser.add_argument('--one-by-one', action='store_true', help='Ask confirmation for each deletion')
    parser.add_argument('--print-list', action='store_true', help='Only print the list of objects that would be deleted')
    args = parser.parse_args()
    dryable.set(args.dry_run)
    logging.info(args)
    return args


def prepare_main_logger():
    logger = logging.getLogger()
    # Logging (split between stderr and stdout)
    formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')
    h1 = logging.StreamHandler(sys.stdout)
    h1.setLevel(logging.DEBUG)
    h1.addFilter(lambda record: record.levelno <= logging.INFO) # filter out everything that is above INFO level
    h1.setFormatter(formatter)
    logger.addHandler(h1)
    h2 = logging.StreamHandler(sys.stderr)
    h2.setLevel(logging.WARNING)     # take only warnings and error logs
    h2.setFormatter(formatter)
    logger.addHandler(h2)


def run(args):
    ccdb = Ccdb(args.url)
    versions = ccdb.getVersionsList(args.path + "/.*", args.from_ts, args.to_ts)
    logging.debug(versions)
    logging.info("Here are the objects that are going to be deleted: ")

    if args.print_list:
        for v in versions:
            logging.info(v)
        logging.info(f"Number of items: {len(versions)}")
        exit(0)

    logging.info(f"Number of items: {len(versions)}")

    logging.warning("****** ARE YOU ABSOLUTELY SURE YOU WANT TO CONTINUE ? ******")
    answer = input("Yes/No \n  ")
    if answer.lower() not in ["y", "yes"]:
        exit(0)

    for v in versions:
        logging.info(f"Ready to delete {v}")
        if args.one_by_one:
            answer = input("  Continue? y/n\n  ")
            if answer.lower() in ["y", "yes"]:
                ccdb.deleteVersion(v)
            elif answer.lower() in ["n", "no"]:
                logging.info("   skipping")
            else:
                logging.error("   wrong input, skipping")
        else:
            ccdb.deleteVersion(v)

    logging.info(f"Deleted items: {len(versions)}")

# ****************
# We start here !
# ****************

def main():
    start_time = time.time()
    prepare_main_logger()

    # Parse arguments
    args = parseArgs()
    logging.getLogger().setLevel(int(args.log_level))

    run(args)


if __name__ == "__main__":
    main()
