#!/usr/bin/env python

from subprocess import Popen, PIPE
from pathlib import Path
from pyPheWAS.pyPhewasCorev2 import print_start_msg
from pyPheWAS.pyPhewasExplorerCore import run_Explorer_GUI
import argparse


"""
Print Start Message
"""
print_start_msg()
print('\npyPheWAS Explorer: Interactive Visualization of PheDAS models\n')

"""
Retrieve and validate all arguments.
"""
parser = argparse.ArgumentParser(description='pyPheWAS Explorer Launch Script')
parser.add_argument('indir', type=str, help='Input directory for pyPheWAS analysis')
parser.add_argument('--response', type=str, required=False, default='target', help='Name of column to use as the response (dependent) variable')
args = parser.parse_args()

data_path = Path(args.indir)
response = args.response

# Assert that valid directory was given
assert data_path.exists(), "%s does not exist" % data_path
assert data_path.is_dir(), "%s is not a valid directory" % data_path

# Assert that required input files exist
group_f = data_path / "group.csv"
assert group_f.exists(), "%s does not contain a group file (group.csv)" % data_path

icd_f = data_path / "icds.csv"
bin_fm_f = data_path / "binary_feature_matrix.csv"
cnt_fm_f = data_path / "count_feature_matrix.csv"
dur_fm_f = data_path / "duration_feature_matrix.csv"
FMs_exist = bin_fm_f.exists() & cnt_fm_f.exists() & dur_fm_f.exists()
assert icd_f.exists() | FMs_exist, "%s does not contain an EMR file (icds.csv)" % data_path

print("Setting up pyPheWAS Explorer using data found in %s" % data_path)


"""
Launch the servers
"""

# Launch the flask server (Back End) as a subprocess
exec_path = Path(__file__).parent.absolute()/'pyPhewasExplorerBackEnd'
process = Popen('python %s %s --response %s' %(exec_path, data_path.resolve(), response), shell=True)

# Launch the simple HTTP server (Front End) as the main process
run_Explorer_GUI()
