#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015, A. Murat Eren
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.

import os
import sys
import argparse
import IlluminaUtils.utils.helperfunctions as h
import IlluminaUtils.utils.terminal as terminal

run = terminal.Run()
progress = terminal.Progress()

general_section = '''[general]
project_name = %(project_name)s
researcher_email = %(e_mail)s
input_directory = %(input_dir)s
output_directory = %(output_dir)s\n\n'''

files_section = '''[files]
pair_1 = %(read_1)s
pair_2 = %(read_2)s\n\n'''

prefixes_section = '''
[prefixes]
%(prefix_text)s
'''

I = lambda x: os.path.abspath(os.path.dirname(x.split(',')[0].strip()) or '.')
D = lambda x: ','.join([os.path.basename(p).strip() for p in [n for n in x.split(',')]])

class ConfigGenerator:
    def __init__(self, args):
        self.args = args
        self.samples_config = h.get_TAB_delimited_file_as_dictionary(args.samples_config)
        self.output_dir = os.path.abspath(args.output_dir) if args.output_dir else os.path.dirname(os.path.abspath(args.samples_config))
        self.r1_prefix = args.r1_prefix
        self.r2_prefix = args.r2_prefix
        self.e_mail = args.e_mail

        run.info('Report', 'Read for %d samples is read' % len(self.samples_config))
        run.info('Output directory set in configs', self.output_dir)
        run.info('Prefix for R1', self.r1_prefix)
        run.info('Prefix for R2', self.r2_prefix)


    def _run(self):
        progress.new('Generating config files')

        if not os.path.exists(self.output_dir):
            progress.end()
            print("\n\tError: Output directory %s does not exist.\n" % self.output_dir)
            sys.exit(1)

        for sample in self.samples_config:
            r1_input_path = I(self.samples_config[sample]['r1'])
            r2_input_path = I(self.samples_config[sample]['r2'])

            if r1_input_path != r2_input_path:
                progress.end()
                print("\n\tError: R1 path is not identical to R2 path for %s.\n" % sample)
                sys.exit(2)

            if not os.path.exists(r1_input_path):
                progress.end()
                print("\n\tError: Input paths for %s do not work...\n" % sample)
                sys.exit(3)

            progress.update('%s ...' % sample)
            ini = open(os.path.join(self.output_dir, sample + '.ini'), 'w')
            ini.write(general_section % {'project_name': sample,
                                         'e_mail': self.e_mail,
                                         'input_dir': r1_input_path,
                                         'output_dir': self.output_dir})

            ini.write(files_section % {'read_1': D(self.samples_config[sample]['r1']),
                                       'read_2': D(self.samples_config[sample]['r2'])})

            prefix_text = ''
            if self.r1_prefix:
                prefix_text += 'pair_1_prefix = %s\n' % self.r1_prefix
            if self.r2_prefix:
                prefix_text += 'pair_2_prefix = %s\n' % self.r2_prefix
            if len(prefix_text):
                ini.write(prefixes_section % {'prefix_text': prefix_text})

            ini.close()

        progress.end()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Generate config files for demultiplexed FASTQ files')

    parser.add_argument('samples_config', metavar = 'FILE',
                        help = 'TAB-delimited file to describe where samples are. The header line should be "sample",\
                                "r1", and "r2". Each row should list the sample name in the first column, and full path\
                                for r1 and r2. This output is automatically generated by the iu-demultiplex script.')
    parser.add_argument('--r1-prefix', metavar = 'REGEXP', default = None,
                        help = 'Prefix for Read 1 to be put in every config file.')
    parser.add_argument('--r2-prefix', metavar = 'REGEXP', default = None,
                        help = 'Prefix for Read 2.')
    parser.add_argument('--e-mail', metavar = 'E-MAIL', default = 'u@example.edu',
                        help = 'E-mail address (currently is not used for anything)')
    parser.add_argument('-o', '--output-dir', metavar = 'DIRECTORY', default = None,
                        help = 'Directory for output storage. INI files will also be generated in\
                                this directory.')

    try:
        c = ConfigGenerator(parser.parse_args())
        c._run()
    except h.ConfigError as e:
        print(e)
        sys.exit(-1)
