#!/usr/bin/env python

import os
import time
import argparse
from functools import partial


def get_argparser():
    """Get argument parser."""
    parser = argparse.ArgumentParser(
        description=("Diverse Radio Astronomy Tools for Imaging and Calibration"))
    subparsers = parser.add_subparsers(help='commands')
    list_parser = subparsers.add_parser('run', help='Run notebook server')
    list_parser.add_argument('--port', action='store', help='Notebook server port')
    argument = partial(parser.add_argument)
    argument("-gn", "--generate_notebooks",
             default=False, action='store_true',
             help='Generate default notebook files (.ipynb format)')
    return parser

def generate_notebooks():
    """Generate drasticali notebooks"""
    time_start_load = time.time()
    from shutil import copyfile
    import drasticali
    print("## Getting notebook files.")
    drasticali_files = ['drasticali-add.ipynb',
                        'drasticali-edit.ipynb',
                        'drasticali-run.ipynb',
                        'drasticali-inspect.ipynb']
    DRASTICALI_PATH = os.path.dirname(os.path.dirname(os.path.abspath(drasticali.__file__)))
    copyfile('{}/{}/{}'.format(DRASTICALI_PATH, 'drasticali', drasticali_files[0]),
             drasticali_files[0])
    print(drasticali_files[0])
    copyfile('{}/{}/{}'.format(DRASTICALI_PATH, 'drasticali', drasticali_files[1]),
             drasticali_files[1])
    print(drasticali_files[1])
    copyfile('{}/{}/{}'.format(DRASTICALI_PATH, 'drasticali', drasticali_files[2]),
             drasticali_files[2])
    print(drasticali_files[2])
    copyfile('{}/{}/{}'.format(DRASTICALI_PATH, 'drasticali', drasticali_files[3]),
             drasticali_files[3])
    print(drasticali_files[3])
    print("## Done ({0:.3f}s)".format(time.time() - time_start_load))

def run_notebook(port):
    """Run the notebooks"""
    import subprocess
    bashCommand1 = "jupyter-nbextension enable --py widgetsnbextension --sys-prefix"
    bashCommand2 = "jupyter-nbextension install --py jupyter_dashboards --sys-prefix"
    bashCommand3 = "jupyter-nbextension enable --py jupyter_dashboards --sys-prefix"
    bashCommand4 = "jupyter-notebook --NotebookApp.iopub_data_rate_limit=1000000000 --port={} --no-browser".format(port)
    process = subprocess.Popen(bashCommand1.split(), stdout=subprocess.PIPE, shell=True)
    process = subprocess.Popen(bashCommand2.split(), stdout=subprocess.PIPE, shell=True)
    process = subprocess.Popen(bashCommand3.split(), stdout=subprocess.PIPE, shell=True)
    process = subprocess.Popen(bashCommand4.split(), stdout=subprocess.PIPE, shell=True)

def main():
    """Main function."""
    parser = get_argparser()
    args = parser.parse_args()
    if args.generate_notebooks:
        generate_notebooks()
    port = getattr(args, 'port', 0)
    if port:
       run_notebook(port)
    elif port is None:
       run_notebook('8888')

main()
