#!/usr/bin/env python3
# encoding: utf-8
'''
sequences -- shortdesc

sequences is a description

It defines classes_and_methods

Tested on a Mac and Linux computer

@author:     Sheean Spoel
            
@copyright:  2013 Universiteit van Amsterdam. All rights reserved. 
            
@license:    MIT

@contact:    sheean@sheean.nl
@deffield    updated: Updated
'''
import sys
import os

from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter

from Lib import recording
from Lib import stimuli

__version__ = 0.1
__date__ = '2013-05-22'
__updated__ = '2013-05-22'

def main(argv):
    program_name = os.path.basename(sys.argv[0])
    program_version = "v%s" % __version__
    program_build_date = str(__updated__)
    program_version_message = '%%(prog)s %s (%s)' % (program_version, program_build_date)
    program_shortdesc = __import__('__main__').__doc__.split("\n")[1]
    program_license = '''%s

  Created by Sheean Spoel on %s.
  Copyright © 2013 Universiteit van Amsterdam. All rights reserved.
  
  Permission is hereby granted, free of charge, to any person obtaining a 
  copy of this software and associated documentation files (the "Software"), 
  to deal in the Software without restriction, including without limitation the 
  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 
  sell copies of the Software, and to permit persons to whom the Software is 
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in 
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
  SOFTWARE.

USAGE
''' % (program_shortdesc, str(__date__))

    try:
        # Setup argument parser
        parser = ArgumentParser(description=program_license, formatter_class=RawDescriptionHelpFormatter)
        parser.add_argument("-i", "--in", dest="inpath", 
                            help="set input path (default: %(default)s)", 
                            metavar="FILE")
        parser.add_argument("-o", "--out", dest="outpath", 
                            help="set output path (default: %(default)s)", 
                            metavar="FILE")
        parser.add_argument("-w", "--words", dest="words", 
                            help="set word/carriers CSV filename (default: %(default)s)")
        parser.add_argument("-c", "--control", dest="control", 
                            help="set control word")
        parser.add_argument("-v", 
                            "--verbose", 
                            dest="verbose", 
                            type=int,
                            help="set verbosity level (default: %(default)s)")
        parser.add_argument("-sg", "--stimuli_groups", 
                            dest="stimuli_groups",
                            type=int,
                            help="The number of times a group of stimuli should be generated.")
        parser.add_argument("-el", "--enumeration_length",
                            dest="enumeration_length",
                            help="Min and max enumeration length, separated by comma. E.g. 2,5")
        parser.add_argument("-cj", "--conjunction", dest="conjunction", help="Conjunction to use between the last two words in a stimulus. E.g. 'and'")
        parser.add_argument("-r", "--record", dest="record", help="Do a recording (default: %(default)s)")
        parser.add_argument("-sid", "--subject_id", dest="subject_id",
                            help="Subject identifier e.g. S001. Required when recording. If this is specified a stimuli file is written, regardless of whether or not a recording will follow.")
        parser.add_argument("-s", "--sentences", dest="sentences",
                            help="File to read the sentences from, if this is omitted or set to 'generate' sentences are generated.")
        # set defaults
        parser.set_defaults(outpath="./Output", 
                            inpath="./Input",
                            words="cities.txt",
                            control="Venlo",
                            stimuli_groups=4,
                            enumeration_length="2,5",
                            conjunction="en",
                            verbose=0,
                            sentences="generate",
                            record=0)
        
        # process options
        opts = parser.parse_args(argv)
        
        if opts.verbose > 0:
            print("verbosity level = %d" % opts.verbose)
        
        words = opts.inpath + "/Words/" + opts.words
        carriers = opts.inpath + "/Carriers/" + opts.words
        control_word = opts.control
        stimuli_groups = opts.stimuli_groups
        min_enumeration_length, max_enumeration_length = [int(x) for x in
            opts.enumeration_length.split(',')]
        conjunction = opts.conjunction
        verbose = opts.verbose
        
        # MAIN BODY #
        if opts.sentences != "generate":
            # get the file with sentences
            generated_stimuli = None
            with open(opts.sentences, 'rt') as file:
                sentences = [line.replace('\n', '') 
                             for line in file.readlines()][::2]
        else:
            generated_stimuli = stimuli.generate_sentences(
                words, 
                carriers, 
                control_word, 
                stimuli_groups, 
                min_enumeration_length, 
                max_enumeration_length, 
                conjunction, 
                verbose > 0)
            
            sentences = [x[0] for x in generated_stimuli]
            
            if verbose:
                # output the generated sentences to console
                print("# Generated sentences")
                for stimulus in generated_stimuli:
                    print(stimulus[0])
                    print(stimulus[1])
        
            if opts.subject_id != None:
                # write the generated sentences to file
                fname = opts.outpath + '/Stimuli/' + opts.subject_id + '.txt'
                if os.path.isfile(fname):
                    raise(Exception("File already written!"))
                
                file = open(fname, 'w')
                
                for stimulus in generated_stimuli:
                    file.write(stimulus[0] + '\n')
                    file.write(str(stimulus[1]) + '\n')
                    
                file.close()
            
        if opts.record:
            # start the recording of the subject!
            if opts.subject_id == None:
                raise(Exception("Subject identifier not specified!"))
            output = opts.outpath + "/Recordings/" + opts.subject_id + "/"
    
            if os.path.exists(output):
                raise(Exception('Output folder "' + output + '" already exists!'))
            os.makedirs(output)
            
            recording.start(sentences, output)
            
    except Exception as e:
        indent = len(program_name) * " "
        sys.stderr.write(program_name + ": " + repr(e) + "\n")
        sys.stderr.write(indent + "  for help use --help\n\n")
        raise(e)

main(sys.argv[1:])
