# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_config.ipynb.

# %% auto 0
__all__ = ['win_find_path', 'mac_find_path', 'find_path', 'find_dir_edition', 'set_pystata_path', 'launch_stata', 'get_config']

# %% ../nbs/00_config.ipynb 5
import os
import sys
import platform
from shutil import which
from pathlib import Path
from packaging import version
from configparser import ConfigParser, NoSectionError

# %% ../nbs/00_config.ipynb 6
def win_find_path():
    import winreg
    reg = winreg.ConnectRegistry(None, winreg.HKEY_CLASSES_ROOT)
    subkeys = [r'Stata17Do\shell\do\command',
                r'Stata18Do\shell\do\command',
                r'Stata19Do\shell\do\command']

    fpath = ''
    for subkey in subkeys:
        try:
            key = winreg.OpenKey(reg, subkey)
            fpath = winreg.QueryValue(key, None).split('"')[1]
        except FileNotFoundError:
            pass
        if fpath:
            break

    return fpath


def mac_find_path():
    """
    Attempt to find Stata path on macOS when not on user's PATH.
    Modified from stata_kernel's original to only location "Applications/Stata". 

    Returns:
        (str): Path to Stata. Empty string if not found.
    """
    path = Path('/Applications/Stata')
    if not path.exists():
        return ''
    else:
        return str(path)

# %% ../nbs/00_config.ipynb 7
def find_path():
    if os.getenv('CONTINUOUS_INTEGRATION'):
        print('WARNING: Running as CI; Stata path not set correctly')
        return 'stata'
    if platform.system() == 'Windows':
        return win_find_path()
    elif platform.system() == 'Darwin':
        return mac_find_path()
    else:
        for i in ['stata-mp', 'stata-se', 'stata']:
            stata_path = which(i)
            if stata_path:
                break
        return stata_path

# %% ../nbs/00_config.ipynb 9
def find_dir_edition():
    stata_path = find_path()
    if stata_path is None:
        raise OSError("Stata path not found.")
    stata_dir = str(os.path.dirname(stata_path))
    stata_exe = str(os.path.basename(stata_path)).lower()

    edition = 'be'
    for e in ('se','mp'):
        if stata_exe.find(e) > -1:
            edition = e            
    return (stata_dir,edition)

# %% ../nbs/00_config.ipynb 10
def set_pystata_path(path=None):
    if path == None:
        path, _ = find_dir_edition()
    if not os.path.isdir(path):
        raise OSError(path + ' is invalid')
    if not os.path.isdir(os.path.join(path, 'utilities')):
        raise OSError(path + " is not Stata's installation path")
    sys.path.append(os.path.join(path, 'utilities'))

# %% ../nbs/00_config.ipynb 11
def launch_stata(path=None, edition=None, splash=True):
    """
    We modify stata_setup to make splash screen optional
    """
    if path == None or edition == None:
        path_found, edition_found = find_dir_edition()
        path = path_found if path==None else path
        edition = edition_found if edition==None else edition
    try:
        set_pystata_path(path)
    except OSError as err:
        pass
    import pystata
    if version.parse(pystata.__version__) >= version.parse("0.1.1"):
        # Splash message control is a new feature of pystata-0.1.1
        pystata.config.init(edition,splash=splash)
    else:
        pystata.config.init(edition)

# %% ../nbs/00_config.ipynb 14
def get_config():
    """First check if a configuration file exists. If not, try `find_dir_edition`."""
    global_config_path = Path(os.path.join(sys.prefix,'etc','nbstata.conf'))
    user_config_path = Path('~/.nbstata.conf').expanduser()
    env = {'stata_dir': None,
           'edition': None,
           'graph_format': 'png',
           'echo': 'None',
           'splash': 'False',
           'missing': '.',
          }
    for cpath in (global_config_path, user_config_path):
        try:
            if cpath.is_file():
                config = ConfigParser()
                config.read(str(cpath))
                env.update(dict(config.items('nbstata')))
        except:
            pass
    if env['stata_dir']==None or env['edition']==None:     
        stata_dir,stata_ed = find_dir_edition()     
        default_env = {'stata_dir': stata_dir, 'edition': stata_ed}
        env.update(default_env)
    if env['echo'] not in {'True', 'False', 'None'}:
        env['echo'] = 'None'
    return env
