"""param_file.py."""
import logging
import os
from typing import Dict, List, Union

import simulators


def parse_paramfile(param_file: str, path: str = None) -> Dict[str, Union[str, float, List[float]]]:
    """Extract orbit and stellar parameters from parameter file.

    Parameters
    ----------
    param_file: str
        Filename of parameter file.
    path: str [optional]
        Path to directory of filename.

    Returns
    --------
    parameters: dict
        Parameters as a {param: value} dictionary.
    """
    if path is not None:
        param_file = os.path.join(path, param_file)
    parameters = dict()
    if not os.path.exists(param_file):
        raise Exception("Invalid Arguments, expected a file that exists not. {0}".format(param_file))

    with open(param_file, 'r') as f:
        for line in f:
            if line.startswith("#"):
                pass
            else:
                if '#' in line:  # Remove comment from end of line
                    line = line.split("#")[0]
                if line.endswith("="):
                    logging.warning(("Parameter missing value in {0}.\nLine = {1}."
                                     " Value set to None.").format(param_file, line))
                    line = line + " None"  # Add None value when parameter is missing
                par, val = line.lower().split('=')
                par, val = par.strip(), val.strip()
                if (val.startswith("[") and val.endswith("]")) or ("," in val):  # Val is a list
                    parameters[par] = parse_list_string(val)
                else:
                    try:
                        parameters[par] = float(val)  # Turn parameters to floats if possible.
                    except ValueError:
                        parameters[par] = val

    return parameters


def parse_list_string(string: str) -> List[Union[str, float]]:
    """Parse list of floats out of a string."""
    string = string.replace("[", "").replace("]", "").strip()
    list_str = string.split(",")
    try:
        return [float(val) for val in list_str]
    except ValueError as e:
        # Can't turn into floats.
        return [val.strip() for val in list_str]


def get_host_params(star):
    """Find host star parameters from param file."""
    params = load_paramfile(star)
    return params["temp"], params["logg"], params["fe_h"]


def load_paramfile(star):
    """Load parameter file with config path."""
    # test assert for now
    param_file = "{0}_params.dat".format(star)

    return parse_paramfile(param_file, simulators.paths["parameters"])

@@ -194,24 +194,79 @@
 t%5Bfloat%5D%5D%5D:%0A
+    # type: (str, str) -%3E Dict%5Bstr, Union%5Bstr, float%5D%5D%0A
     %22%22%22Extra
@@ -318,16 +318,16 @@
 r file.%0A
-
 %0A    Par
@@ -675,16 +675,54 @@
 = dict()
+  # type: Dict%5Bstr, Union%5Bstr, float%5D%5D
 %0A    if 
@@ -951,16 +951,46 @@
 ith(%22#%22)
+ or line.isspace() or not line
 :%0A      
@@ -2712,8 +2712,1144 @@
 ters%22%5D)%0A
+%0A%0Adef parse_obslist(fname, path=None):%0A    # type: (str, str) -%3E List%5Bstr%5D%0A    %22%22%22Parse Obslist file containing list of dates/times.%0A%0A    Parameters%0A    ----------%0A    fname: str%0A        Filename of obs_list file.%0A    path: str %5Boptional%5D%0A        Path to directory of filename.%0A%0A    Returns%0A    --------%0A    times: list of strings%0A        Observation times in a list.%0A    %22%22%22%0A    if path is not None:%0A        fname = os.path.join(path, fname)%0A    if not os.path.exists(fname):%0A        logging.warning(%22Obs_list file given does not exist. %7B%7D%22.format(fname))%0A%0A    obstimes = list()%0A    with open(fname, 'r') as f:%0A        for line in f:%0A            if line.startswith(%22#%22) or line.isspace() or not line:    # Ignores comments and blank/empty lines.%0A                continue%0A            else:%0A                if %22#%22 in line:   # Remove comment from end of line%0A                    line = line.split(%22#%22)%5B0%5D%0A                if %22.%22 in line:%0A                    line = line.split(%22.%22)%5B0%5D   # remove fractions of seconds.%0A                obstimes.append(line.strip())%0A        logging.debug(%22obstimes = %7B%7D%22,format(obstimes))%0A    return obstimes

update paramfile parser