__all__ = ['FunctionBuilder']

from mcpack import Function, FunctionTag

from . import __version__
from .resource import ResourceBuilder


class FunctionBuilder(ResourceBuilder):
    guard_name = 'function'

    def __init__(self, parent, name, resource):
        super().__init__(parent, name, resource)
        self.function_body = (f'# Generated by endermite v{__version__}\n'
                              '# Modifications will be overwritten\n\n')

    def register_command(self, command_object):
        self.resource.append(command_object)

    def build(self):
        self.function_body += '\n'.join(map(str, self.resource)) + '\n'

    def populate(self, pack):
        super().populate(pack)
        pack[self.name] = Function(self.function_body)


class FunctionTagBuilder(ResourceBuilder):
    guard_name = 'function tag'

    def __init__(self, parent, name, resource):
        super().__init__(parent, name, resource)
        self.values = []

    def build(self):
        self.values.extend(map(str, self.resource))

    def populate(self, pack):
        super().populate(pack)
        namespace, name = self.name.split(':')
        tags = pack[namespace].function_tags

        function_tag = tags.get(name, FunctionTag([]))
        function_tag.values.extend(self.values)
        tags[name] = function_tag
