import os

from urlparse import urlparse
from netrc import netrc
from lacli.log import getLogger
from lacli.decorators import cached_property


API_URL = 'https://www.longaccess.com/api/v1/'


class LaRegistry(object):
    cache = None
    prefs = None
    session = None

    def __init__(self, cache, prefs, cmd):
        if prefs['api'].get('url') is None:
            prefs['api']['url'] = API_URL
        self.cache = cache
        self.prefs = prefs
        self.cmd = cmd
        self.session = self.new_session()

    def init_prefs(self):
        prefs = self.prefs['api']
        if prefs.get('url') is None:
            prefs['url'] = API_URL
        if not prefs['user']:
            prefs['user'] = self._saved_session[0]
            prefs['pass'] = self._saved_session[1]
        return prefs

    def new_session(self, prefs=None):
        if not prefs:
            prefs = self.init_prefs()
        return self.prefs['api']['factory'](prefs)

    @cached_property
    def _saved_session(self):
        hostname = urlparse(self.prefs['api']['url']).hostname
        try:
            for host, creds in netrc().hosts.iteritems():
                if host == hostname:
                    return (creds[0], creds[2])
        except:
            getLogger().debug("Couldn't read from netrc", exc_info=True)
        return (None, None)

    def save_session(self, *args):
        self._saved_session = tuple(args)
        with open(os.path.expanduser("~/.netrc"), 'a') as f:
            f.write("machine {} login {} password {}\n".format(
                urlparse(self.session.url).hostname,
                self._saved_session[0],
                self._saved_session[1]))

@@ -952,16 +952,251 @@
 prefs)%0A%0A
+    def netarsee(self):%0A        ours = os.path.join(self.cache.home, %22.netrc%22)%0A        users = os.path.expanduser('~/.netrc')%0A        if not os.path.exists(ours) and os.path.exists(users):%0A            return users%0A        return ours%0A%0A
     @cac
@@ -1208,16 +1208,16 @@
 roperty%0A
-
     def 
@@ -1351,16 +1351,31 @@
 n netrc(
+self.netarsee()
 ).hosts.
@@ -1689,37 +1689,22 @@
 pen(
-os.path.expanduser(%22~/.netrc%22
+self.netarsee(
 ), '

use our own netrc if we can't find the users