import os
import sys
import subprocess
import re
import webbrowser
from surround import Config

CONFIG = Config(os.path.dirname(__file__))
DOIT_CONFIG = {{'verbosity':2}}
PACKAGE_PATH = os.path.basename(CONFIG["package_path"])
IMAGE = "%s/%s:%s" % (CONFIG["company"], CONFIG["image"], CONFIG["version"])

PARAMS = [
    {{
        'name': 'args',
        'long': 'args',
        'type': str,
        'default': ""
    }}
]

def task_status():
    """Show information about the project such as available runners and assemblers"""
    return {{
        'actions': ["%s -m %s --status" % (sys.executable, PACKAGE_PATH)]
    }}

def task_build():
    """Build the Docker image for the current project"""
    return {{
        'actions': ['docker build --tag=%s .' % IMAGE],
        'params': PARAMS
    }}

def task_remove():
    """Remove the Docker image for the current project"""
    return {{
        'actions': ['docker rmi %s -f' % IMAGE],
        'params': PARAMS
    }}

def task_dev():
    """Run the main task for the project"""
    return {{
        'actions': ["docker run --volume \"%s/\":/app %s python3 -m %s %s" % (CONFIG["volume_path"], IMAGE, PACKAGE_PATH, "%(args)s")],
        'params': PARAMS
    }}

def task_interactive():
    """Run the Docker container in interactive mode"""
    def run():
        process = subprocess.Popen(['docker', 'run', '-it', '--rm', '-w', '/app', '--volume', '%s/:/app' % CONFIG['volume_path'], IMAGE, 'bash'], encoding='utf-8')
        process.wait()

    return {{
        'actions': [run]
    }}

def task_prod():
    """Run the main task inside a Docker container for use in production """
    return {{
        'actions': ["docker run %s python3 -m %s %s" % (IMAGE, PACKAGE_PATH, "%(args)s")],
        'task_dep': ["build"],
        'params': PARAMS
    }}

def task_train():
    """Run training mode inside the container"""
    output_path = CONFIG["volume_path"] + "/output"
    data_path = CONFIG["volume_path"] + "/input"

    return {{
        'actions': ["docker run --volume \"%s\":/app/output --volume \"%s\":/app/input %s python3 -m {project_name} --mode train %s" % (output_path, data_path, IMAGE, "%(args)s")],
        'params': PARAMS
    }}

def task_batch():
    """Run batch mode inside the container"""
    output_path = CONFIG["volume_path"] + "/output"
    data_path = CONFIG["volume_path"] + "/input"

    return {{
        'actions': ["docker run --volume \"%s\":/app/output --volume \"%s\":/app/input %s python3 -m {project_name} --mode batch %s" % (output_path, data_path, IMAGE, "%(args)s")],
        'params': PARAMS
    }}

def task_train_local():
    """Run training mode locally"""
    return {{
        'basename': 'trainLocal',
        'actions': ["%s -m %s --mode train %s" % (sys.executable, PACKAGE_PATH, "%(args)s")],
        'params': PARAMS
    }}

def task_batch_local():
    """Run batch mode locally"""
    return {{
        'basename': 'batchLocal',
        'actions': ["%s -m %s --mode batch %s" % (sys.executable, PACKAGE_PATH, "%(args)s")],
        'params': PARAMS
    }}


def task_jupyter():
    command = "pip install -r /app/requirements.txt; mkdir /etc/ipython; echo \"c.InteractiveShellApp.extensions.append('autoreload')\nc.InteractiveShellApp.exec_lines = ['%autoreload 2', 'import sys', 'sys.path.append(\\'../\\')']\" > /etc/ipython/ipython_config.py; /usr/local/bin/start.sh jupyter notebook --NotebookApp.token=''"
    
    def run_command():
        process = subprocess.Popen([
            "docker", 
            "run",
            "--rm",
            "--name", "{project_name}_surround_notebook",
            "--volume", "%s:/app" % CONFIG['volume_path'], 
            "-p", "55910:8888",
            "--user", "root",
            "-w", "/app",
            "jupyter/base-notebook:307ad2bb5fce", 
            "bash",  "-c", command], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8')

        print("Starting jupyter notbook server...\n")
        
        # Get the IP address of the container, otherwise use localhost
        ip_process = subprocess.Popen(['docker-machine', 'ip'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8')
        ip_process.wait()

        ip_output = ip_process.stdout.readline().rstrip()

        if re.match(r"^(\d{{1,3}}\.){{3}}\d{{1,3}}$", ip_output):
            host = ip_output
        else:
            host = "localhost"

        # Wait for the notebook server to be up before loading browser
        while True:
            line = process.stderr.readline().rstrip() 
            if line and 'Serving notebooks from local directory' in line:
                break
            elif process.poll():
                print("Failed to start the server, check if its not running somewhere else!")

                # Stop any containers that might be running
                process = subprocess.Popen(['docker', 'stop', '{project_name}_surround_notebook'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                process.wait()
                return

        # Open the browser automatically
        webbrowser.open('http://%s:55910/tree' % host, new=2)

        print("Notebook URL: http://%s:55910/tree\n" % host)
        print("Use CTRL+C to stop the server.")

        try:
            process.wait()
        except KeyboardInterrupt:
            pass
        finally:
            print("Closing server...")
            process = subprocess.Popen(['docker', 'stop', '{project_name}_surround_notebook'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            process.wait()
    
    return {{
        'actions': [run_command]
    }}
