#!/usr/bin/python3

import argparse
# import os
import subprocess
import dater

from erimp import Erimp

desc = 'run classing for an issue'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('-v', action='store_true', help='raise verbosity')
parser.add_argument('-b', type=int, help='boxes')
parser.add_argument('-c', type=int, help='cache selections screen')
parser.add_argument('-t', action='store_true', help='end tonight')
parser.add_argument('bapis', metavar='bnp', type=str, nargs='*',
                    help='bits and pieces arguments')
# not supported here
parser.add_argument('-n', action='store_true', help='dry run')
args = parser.parse_args()
e = Erimp(args.bapis, do_verbose=args.v)

leiz = 1
if args.b is not None:
    leiz = args.b
## the caller should give it an issuedate but if it's not there

if e.given_issuedate is None:
    # # use the issuedate of tonight
    issuedate = dater.tonight()
    print(f"class uses {issuedate}.")
else:
    issuedate = e.given_issuedate

class_bin_fufi = e.dirs['bin'] + '/class'
class_call = class_bin_fufi

# # add -t to end tonight
if(args.t is True):
    class_call += ' -t'

# # add -c to cache the selection screen
if(args.c is True):
    class_call += ' -c'

zahl = 0
if leiz == 1:
    logger = e.dirs['log'] + '/class_' + issuedate
    log = f"> {logger}.out 2> {logger}.err"
    s = f"{class_call} {issuedate} {log}"
    if args.n:
        print(s)
    else:
        print(s)
        subprocess.run(s, shell=True)
    quit()

while zahl < leiz:
    zahl += 1
    logger = e.dirs['log'] + '/class_' + issuedate + '_' + str(zahl)
    box = '-b ' + str(zahl) + ':' + str(leiz) + ' ' + issuedate
    log = f"> {logger}.out 2> {logger}.err"
    s = f"{class_call} {box} {log} &"
    if args.n:
        print(s)
    else:
        print(s)
        subprocess.run(s, shell=True)
