import os
import sys
import posixpath
import logging
try:
    from collections import OrderedDict
except ImportError:
    from ordereddict import OrderedDict

from fabric.api import env
from fabric import network

from .conf import DEFAULTS as CONF_DEFAULTS
from .containers import MultiSourceDict, AttributeDict


logger = logging.getLogger('fabdeploy')


def setup_fabdeploy():
    sys.path[0:0] = os.path.dirname(sys.path[0])

    if not hasattr(env, 'conf'):
        env.conf = MultiSourceDict(dict(
            host='%s@localhost' % os.environ['USER'],
        ))
    if not env.hosts:
        env.hosts = [env.conf.host]


def substitute(value, conf):
    if isinstance(value, list):
        for i, v in enumerate(value):
            value[i] = substitute(v, conf)
    elif isinstance(value, basestring):
        value = value % conf
    return value


def process_conf(user_conf, use_defaults=True):
    user_conf = AttributeDict(user_conf or {})
    conf = MultiSourceDict(name='process_conf')

    if use_defaults:
        for k, v in CONF_DEFAULTS.items():
            user_conf.setdefault(k, v)

    if 'address' in user_conf:
        conf.setdefault('address', user_conf.address)
        username, host, _ = network.normalize(conf.address)
        conf.setdefault('user', username)
        conf.setdefault('host', host)

    for k, v in user_conf.items():
        try:
            v = substitute(v, conf)
        except ValueError:
            logger.debug('Can not format %r=%r' % (k, v))

        if k.endswith(('_dir', '_path')) and isinstance(v, (list, tuple)):
            v = posixpath.join(*v).rstrip(posixpath.sep)
        elif k.endswith(('_ldir', '_lpath')) and isinstance(v, (list, tuple)):
            v = os.path.abspath(os.path.join(*v).rstrip(os.sep))

        conf.setdefault(k, v)

    return conf


def setup_conf(user_conf):
    return MultiSourceDict(process_conf(user_conf))


def fabconf(name, base_conf=None, task_kwargs=None):
    if base_conf:
        conf = base_conf.copy()
    else:
        conf = OrderedDict()

    try:
        import fabconf as config
    except ImportError:
        pass
    else:
        name = '%s_CONF' % name.upper()
        conf.update(getattr(config, name))

    if task_kwargs:
        conf.update(task_kwargs)

    env.conf = setup_conf(conf)
    env.hosts = [env.conf.address]

@@ -904,55 +904,8 @@
 e):%0A
-    user_conf = AttributeDict(user_conf or %7B%7D)%0A
     
@@ -978,27 +978,26 @@
         
-for k, v in
+tmp_conf =
  CONF_DE
@@ -1003,24 +1003,22 @@
 EFAULTS.
-items
+copy
 ()
-:
 %0A       
@@ -1022,38 +1022,63 @@
     
-    user_conf.setdefault(k, v)
+tmp_conf.update(user_conf)%0A        user_conf = tmp_conf
 %0A%0A  
@@ -1146,32 +1146,35 @@
 ', user_conf
-.
+%5B'
 address
+'%5D
 )%0A        us
@@ -1209,28 +1209,36 @@
 rmalize(
+user_
 conf
-.
+%5B'
 address
+'%5D
 )%0A      

Improve process_conf