#!/usr/bin/env python
"""  This script recomputes the results presented in Eisenhauer (2017).
"""

# standard library
import subprocess
import argparse
import socket
import shutil
import glob
import sys
import os

# module wide variables
PROJECT_DIR = os.path.dirname(os.path.realpath(__file__))
PYTHON_EXEC = 'python'

RSLT_DIR = PROJECT_DIR + '/results'
PUBLISH_DIR = PROJECT_DIR + '/_recomputed'


def distribute_arguments(parser):
    """ Distribute command line arguments.
    """
    # Process command line arguments
    args = parser.parse_args()

    # Extract arguments
    num_procs = args.num_procs
    is_debug = args.is_debug

    # Check arguments
    assert (is_debug in [True, False])
    assert (isinstance(num_procs, int))
    assert (num_procs > 0)

    # Finishing
    return is_debug, num_procs

''' Execution of module as script.
'''

if __name__ == '__main__':

    parser = argparse.ArgumentParser(
        description='Recompute the results from Eisenhauer (2018).')

    parser.add_argument('--debug', action='store_true', dest='is_debug', help='only three periods')

    parser.add_argument('--procs', action='store', type=int, dest='num_procs', default=1,
        help='use multiple processors')

    # Distribute arguments
    is_debug, num_procs = distribute_arguments(parser)

    # Cleanup
    for dirname in [PUBLISH_DIR, RSLT_DIR]:
        if os.path.exists(dirname):
            shutil.rmtree(dirname)
        os.mkdir(dirname)

    # Recompute the results from the solution and estimation exercise. I start two subprocesses
    # and wait for both to finish before aggregating the results.
    os.system('clear')
    bar = '!' + '-' * 60
    print('\n' + bar)
    print('! Recomputation of Eisenhauer (2017) ')
    print(bar)

    cmd = [PYTHON_EXEC, 'run.py', '--procs', str(num_procs)]
    if is_debug:
        cmd += ['--debug']

    print('\n ... starting on recomputations of Keane & Wolpin (1994) ')
    os.chdir('recomputation')
    for which in ['exact_solution', 'correct_choices', 'monte_carlo']:
        os.chdir(which)
        subprocess.call(cmd)
        os.chdir('../')
    os.chdir('../')
    print(' finished')

    # Create some additional results.
    print('\n ... starting on extensions ')
    os.chdir('extension')
    for which in ['criterions', 'schemes', 'performance', 'smoothing']:
        os.chdir(which)
        subprocess.call(cmd)
        os.chdir('../')
    os.chdir('../')
    print(' finished')

    # Aggregate results from the recomputations.
    os.chdir(RSLT_DIR)
    for request in ['exact_solution', 'correct_choices', 'monte_carlo']:
        os.chdir(request)
        for fname in glob.glob('*.txt') + glob.glob('*.png'):
            shutil.copy(fname, PUBLISH_DIR + '/' + fname)
        os.chdir('../')
    os.chdir('../')

    # Aggregate results from extensions.
    os.chdir(RSLT_DIR)
    for request in ['criterions', 'schemes', 'performance', 'smoothing']:
        os.chdir(request)
        for fname in glob.glob('*.txt') + glob.glob('*.png'):
            shutil.copy(fname, PUBLISH_DIR + '/' + fname)
        if request == 'schemes':
            # I also want to provide the information from the static estimation.
            shutil.copy('static/est.respy.info', PUBLISH_DIR + '/static.txt')
        os.chdir('../')
    os.chdir('../')

    print('\n ... finished computations with aggregation of results\n')
    print(' All output files are available in the _recomputed directory. See ')
    print(' the Appendix for more details.\n\n')
