#!python

import sys
import os

try:
	from loguru import logger
except ModuleNotFoundError:
	sys.exit(f'<loguru> required, try <pip install loguru>.')

sys.path = [os.path.join(os.path.dirname(os.path.realpath(__file__)),'..')] + sys.path

try:
	import argparse as ap
except ModuleNotFoundError:
	logger.error(f'<argparse> required, try <pip install argparse>.')
	sys.exit()

from pandora import version

__author__ = 'Jie Li'
__email__  = 'jeveylijie near 163.com'
__version__ = version.__version__


def read_args(args):
	parent_parser = ap.ArgumentParser(add_help=False)
	parent_parser.add_argument('-v', '--version', action='version',
							version=__version__,
							help='print version information')

	p = ap.ArgumentParser(parents=[parent_parser])
	# create subparsers
	subp = p.add_subparsers(dest='subparser_name')
	# create parser for 'fq2fa' command
	p_fq2fa = subp.add_parser('fq2fa', parents=[parent_parser],
						help='convert fastq to fasta.')
	p_fq2fa.add_argument('--fastq', required=True,
						help='input fastq file (.gz).')

	# create parser for 'fxlength' command
	p_fxlength = subp.add_parser('fxlength', parents=[parent_parser],
						help='count sequence length.')
	p_fxlength.add_argument('--sequence', required=True,
						help='input sequence file.')
	p_fxlength.add_argument('--plot', action='store_true',
						help='set to plot a histogram for length.')

	# create parser for 'avglength' command
	p_avglength = subp.add_parser('avglength', parents=[parent_parser],
						help='average length of input sequences.')
	p_avglength.add_argument('--sequence', required=True,
						help='input sequence file.')
	p_avglength.add_argument('--plot', action='store_true',
						help='set to plot a histogram for length')


	# create parser for check_phred command
	p_phred = subp.add_parser('check_phred', parents=[parent_parser],
						help='check fastq Phred vaule.')
	p_phred.add_argument('--fastq', required=True,
						help='input fastq file.')
	p_phred.add_argument('-n', '--num', type=int, default=1000,
						help='number of sequences for Phred check (1000).')

	# create parser for extract_seq command
	p_extract = subp.add_parser('extract_seq', parents=[parent_parser],
						help='extract sequences using id.')
	p_extract_id = p_extract.add_mutually_exclusive_group()
	p_extract_id.add_argument('--seqid', nargs = '+',
						help='sequence id to extract, seperate by " ".')
	p_extract_id.add_argument('--seqidlist',
						help='id list in file to extract.')
	p_extract.add_argument('--sequence', required=True,
						help='input sequence.')
	p_extract.add_argument('--fastq', action='store_true',
						help='set if input is fastq.')
	p_extract.add_argument('-u', '--unmatch', action='store_true',
						help='set to extract unmatch sequences.')

	# create parser for summary_mag command
	p_summary_mag = subp.add_parser('summary_mag', parents=[parent_parser],
						help='summary high quality mag.')
	p_summary_mag.add_argument('--table', nargs='+', required=True,
						help='input stat table(s) from CheckM, seperate by " ".')
	p_summary_mag.add_argument('--completeness', type=int, default=80,
						help='stat genomes with completeness above this value (80).')
	p_summary_mag.add_argument('--contamination', type=int, default=20,
						help='stat genomes with contamination below this value (20).')


	# create parser for abs2rel command
	p_abs2rel = subp.add_parser('abs2rel', parents=[parent_parser],
						help='insert relative abundance for each sample.')
	p_abs2rel.add_argument('--table', required=True,
						help='input table, column represents sample, \
							row represents OTU, species, MAG etc.')
	p_abs2rel.add_argument('-o', '--out_table', help='otput table, print if not set.')

	if len(args) == 1:
		sys.exit(p.print_help())

	return p.parse_args()


if __name__ == '__main__':

	arg = read_args(sys.argv)
	# print(arg)
	if arg.subparser_name == 'fq2fa':
		from pandora.fq2fa import FQ2FA
		FA2FA.fq2fa(arg.fastq)
	elif arg.subparser_name == 'fxlength':
		from pandora.fxlength import fxLength
		fxLength.fxlength(arg.sequence, arg.plot)
	elif arg.subparser_name == 'avglength':
		from pandora.fxlength import fxLength
		fxLength.fxlength(arg.sequence, arg.plot, True)
	elif arg.subparser_name == 'check_phred':
		from pandora.check_phred import Phred
		Phred.check_phred(arg.fastq, arg.num)
	elif arg.subparser_name == 'extract_seq':
		from pandora.extract_seq import Extract_Seq
		Extract_Seq.extract_seq(arg.seqid, arg.seqidlist, arg.sequence,
								arg.fastq, arg.unmatch)
	elif arg.subparser_name == 'summary_mag':
		from pandora.summary_mag import SummaryMAG
		SummaryMAG.summary_mag(arg.table, arg.completeness, arg.contamination)
	elif arg.subparser_name == 'abs2rel':
		from pandora.abs2rel import Abs2Rel
		Abs2Rel.abs2rel(arg.table, arg.out_table)
	else:
		raise Exception('Unrecognized command.')
