ind = ' '*4
item_stack = []
switch_stack = []
switch_i = 0


class Switch:

    def __init__(self, feature="FEAT_RAILTYPES",
                 expression=None, random=False):
        self.feature = feature
        self.expression = expression
        self.random = random
        self.ranges = []
        global switch_stack
        switch_stack.append(self)
        global switch_i
        self.name = "switch_{}".format(switch_i)
        switch_i += 1

    def add(self, cond, rval):  
        self.ranges.append((cond, rval))

    def nml(self):
        out = []
        if self.random:
            out.append("random_switch ({}, SELF, {}) {{".format(
                self.feature, self.name))
        else:
            out.append("switch ({}, SELF, {}, {}) {{".format(
                self.feature, self.name, self.expression))
        for r in self.ranges:
            try:
                rval = r[1].name
            except AttributeError:
                rval = r[1]
            out.append("{}{}: {};".format(ind, r[0], rval))
        out.append("}")
        return '\n'.join(out)


class Item:

    def __init__(self, feature, name):
        self.feature = feature
        self.name = name
        self.decors = []
        self.props = []
        self.graphics = []
        global item_stack
        item_stack.append(self)

    def add_decor(self, decor):
        self.decors.append(decor)

    def add_graphics(self, cb, value):
        self.graphics.append((cb, value))

    def add_prop(self, prop, value):
        self.props.append((prop, value))

    def nml(self):
        out = []
        out.append("item ({}, {}) {{ property {{".format(
            self.feature, self.name))
        for p in self.props:
            out.append("{}{}: {};".format(ind, p[0], p[1]))
        out.append("}}")
        if self.graphics:
            out.append("item ({}, {}) {{ graphics {{".format(
                self.feature, self.name))
            for g in self.graphics:
                try:
                    rval = g[1].name
                except AttributeError:
                    rval = g[1]
                out.append("{}{}: {};".format(ind, g[0], rval))
            out.append("}}")
        out = '\n'.join(out)
        for d in self.decors:
            out = d.format(out)
        return out
