from _convert_deferred import deferred_conversion, convert_deferred
from .._as import Merge
from .._match import Context
from collections import Mapping
from copy import deepcopy, copy


class DeferredMerge(object):
    def __init__(self, values):
        self._values = values
    
    def _eval(self, evaluator):
        if isinstance(self._values, Mapping):
            return type(self._values)((k, evaluator.eval(v)) for k,v in self._values.iteritems())
        else:
            return type(self._values)(evaluator.eval(i) for i in self._values)


def _deferred_context(context):
    retval = copy(context)
    retval['%'] = convert_deferred(retval['%'], context)
    return retval


@deferred_conversion(Merge)
def _convert_deferred_merge(x, context):
    x = deepcopy(x)
    x._convert_leaf = lambda x:convert_deferred(x, Context())
    x._path = x._path._to_path(context)
    return DeferredMerge(x._convert(_deferred_context(context)))
