###############################################################################
# This file is part of the tango-takeoff project.
#
# Copyright Lund University
#
# Distributed under the GNU GPLv3 license. See LICENSE file for more info.
###############################################################################


class Server:
    def __init__(self, name, host, level):
        self.name = name
        self.host = host
        self.level = level

    def __repr__(self):
        return f"'name: {self.name} level: {self.level} host: {self.host}'"


class ServerGroup:
    def __init__(self, level):
        self.level = level
        self.servers = []

    def add(self, server):
        if server.level != self.level:
            return

        self.servers.append(server)

    def names(self):
        server_names = []

        for server in self.servers:
            server_names.append(server.name)

        return server_names


class ServerGroupCollection:
    def __init__(self, servers=None):
        self.server_groups = []

        if servers:
            for server in servers:
                self.add(server)

    def add(self, server):
        group = self._server_group_for_level(server.level)
        if group is None:
            group = ServerGroup(server.level)
            self.server_groups.append(group)

        group.add(server)

    def _server_group_for_level(self, level):
        for server_group in self.server_groups:
            if server_group.level == level:
                return server_group

    def groups(self):
        return sorted(self.server_groups, key=lambda x: x.level)
