from __future__ import absolute_import
import netrc
import os
import platform

def netrc_name():
    if platform.system().lower() == 'windows':
        return "_netrc"
    else:
        return ".netrc"

def get_netrc_file():
    # TODO: support netrc files in locations other than ~/.netrc
    fname = os.path.join(os.environ['HOME'], netrc_name())
    try:
        netrc_file = netrc.netrc(fname)
    except IOError:
        # if netrc does not exist, touch it
        # from: http://stackoverflow.com/questions/1158076/implement-touch-using-python
        with open(fname, 'a'):
                os.utime(fname, None)
        netrc_file = netrc.netrc(fname)
    
    return netrc_file, fname

def clear_netrc(env):
    netrc_file, fname = get_netrc_file()

    if env == 'prod':
        del netrc_file.hosts['git.gigalixir.com'] 
        del netrc_file.hosts['api.gigalixir.com']
    elif env == 'dev':
        del netrc_file.hosts['localhost']
    elif env == 'test':
        del netrc_file.hosts['git.gigalixir.com'] 
        del netrc_file.hosts['api.gigalixir.com']

    with open(fname, 'w') as fp:
        fp.write(netrc_repr(netrc_file))

def update_netrc(email, key, env):
    netrc_file, fname = get_netrc_file()
    
    if env == 'prod':
        if email is None:
            # is it safe to assume that the email is always there for us to use?
            # is it safe to assume the emails are the same for both?
            (email, _, _) = netrc_file.hosts['api.gigalixir.com']
        netrc_file.hosts['git.gigalixir.com'] = (email, None, key)
        netrc_file.hosts['api.gigalixir.com'] = (email, None, key)
    elif env == 'dev':
        if email is None:
            (email, _, _) = netrc_file.hosts['localhost']
        netrc_file.hosts['localhost'] = (email, None, key)
    elif env == 'test':
        if email is None:
            # is it safe to assume the emails are the same for both?
            (email, _, _) = netrc_file.hosts['api.gigalixir.com']
        netrc_file.hosts['git.gigalixir.com'] = (email, None, key)
        netrc_file.hosts['api.gigalixir.com'] = (email, None, key)
    else:
        raise Exception('Invalid env: %s' % env)

    with open(fname, 'w') as fp:
        fp.write(netrc_repr(netrc_file))

# Copied from https://github.com/enthought/Python-2.7.3/blob/master/Lib/netrc.py#L105
# but uses str() instead of repr(). If the .netrc file uses quotes, repr will treat the quotes
# as part of the value and wrap it in another quote resulting in double quotes. I need to dig
# into this deeper, but this works for now.
def netrc_repr(netrc):
    rep = ""
    for host in sorted(netrc.hosts.keys()):
        attrs = netrc.hosts[host]
        rep = rep + "machine "+ host + "\n\tlogin " + str(attrs[0]) + "\n"
        if attrs[1]:
            rep = rep + "account " + str(attrs[1])
        rep = rep + "\tpassword " + str(attrs[2]) + "\n"
    for macro in sorted(netrc.macros.keys()):
        rep = rep + "macdef " + macro + "\n"
        for line in netrc.macros[macro]:
            rep = rep + line
        rep = rep + "\n"
    return rep
