#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import logging
import os
import sys
import uuid

import seutils

import qondor

parser = argparse.ArgumentParser()
parser.add_argument('jsonfile', type=str, help='Path to a .json file or a run directory', default='.', nargs='?')
parser.add_argument('-d', '--dry', action='store_true', help='Prints what would happen does not actually submit a job')
parser.add_argument('-v', '--verbose', action='store_true', help='Enable info output')
parser.add_argument('--debug', action='store_true', help='Enable debug output')
parser.add_argument('-c', '--cli', action='store_true', help='Force the job to be submitted by the condor_submit command line via a .jdl file')
parser.add_argument('--no-cache', action='store_true', help='Disable storage element caching')
args = parser.parse_args()

try:
    input = raw_input
except NameError:
    pass
    
def main():
    qondor.logger.setLevel(logging.WARNING)
    if args.verbose:
        qondor.logger.setLevel(logging.INFO)
    if args.debug:
        qondor.logger.setLevel(logging.DEBUG)
    if args.dry: qondor.drymode()
    if not args.dry and not args.no_cache: seutils.use_cache()

    resub = qondor.resubmit.build_resubmission(args.jsonfile)
    resub.print_jobs(only_failed=True)

    n_failed_jobs = 0
    for jobs in resub.job_objects(only_failed=True):
        n_failed_jobs += len(jobs)

    while True:
        answer = input('resubmit {} jobs [y/n]? '.format(n_failed_jobs)).lower()
        if answer == 'y':
            break
        elif answer == 'n':
            return

    resub.resubmit(cli=args.cli)


if __name__ == '__main__':
    main()