#!/usr/bin/env python3

import logging
import argparse
import dryable
from qcrepocleaner.Ccdb import Ccdb
from qcrepocleaner.binUtils import prepare_main_logger

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('--only-path-no-subdir', action='store_true', help='Do not process the subfolders, i.e. do not '
                                                                 'add .* at the end of the path.')
    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 run(args):
    ccdb = Ccdb(args.url)
    path = args.path+"/" if args.only_path_no_subdir else args.path + "/.*"
    versions = ccdb.getVersionsList(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():
    prepare_main_logger()

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

    run(args)


if __name__ == "__main__":
    main()
