#!/usr/env/bin python
"""
RefChef - Genome References Management Software
"""

import argparse
import os
from refchef import config
from refchef.utils import *
from refchef.table_utils import read_menu
from refchef.references import *
from refchef.github_utils import *
import glob

parser = argparse.ArgumentParser(description='Controls how to run the reference parser')

parser.add_argument('-e', '--execute', help = 'Executes the YAML file, either the new if it exists or the master if not', action='store_true')
parser.add_argument('--new', '-n', type=str, help = 'Denotes the new YAML')
parser.add_argument('--update', '-u', action='store_true')
parser.add_argument('--skip', help = 'Skip appending the new YAML (mainly for testing)', action='store_true')

# Parse arguments
arguments = parser.parse_args()

# Check for config file.
conf = config.config_check()

# Read menu (master.yaml)
master = read_menu(conf)
# Get full path of master yaml
master_path = "master.yaml"

# If new argument, append that to master and reload master.
if arguments.new is not None:
	new_append(arguments.new, master_path, conf)
	master = read_menu(conf)

installed_references = [r.split("/")[-1] for r in glob.glob(conf.reference_dir + "/*")]
# Get keys from master yaml
ref_keys = list(master.keys())

if arguments.execute:
	run = referenceHandler(conf, errorBehavior = processLogical(conf.break_on_error))
	#print(referenceKeys)
	for k in range(0, len(ref_keys)):
		if ref_keys[k] not in installed_references:
			run.processEntry(conf.reference_dir, master.get(ref_keys[k]))

if arguments.update:
	update_repository(conf)
