# networks.py is part of Panopticon.

# Panopticon is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# Panopticon is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with Panopticon.  If not, see <http://www.gnu.org/licenses/>.

from panopticon.core.base import PanopticonManager, ManagedPanopticonAttribute
from panopticon.core.computers import Computer
from panopticon.core.util.managers import SmartManager

class NetworkComputerManager(SmartManager):
    _managed_obj_name = "network"
    _manager_attribute_class = Computer

class Network(ManagedPanopticonAttribute):
    computers = NetworkComputerManager()

    def __init__(self, dns_base="", ip_base="", panopticon=None, name=None):
        super(Network, self).__init__(name=name, panopticon=panopticon)
        self.dns_base = dns_base
        self.ip_base = ip_base

    def get_ip(self, ip):
        return "%s.%s" % (self.ip_base, ip) if self.ip_base else ip

    def get_dns_name(self, dns):
        return "%s.%s" % (self.dns_base, dns) if self.dns_base else dns

    def _transform_values(self, values):
        """Replaces computers from the list with computer names to avoid 
        duplicated definitions of computers in the tree."""

        computers = values["computers"]
        computer_names = set([ name for name, v in computers.iteritems() ])
        del values["computers"]
        values["computer_names"] = computer_names
        return values

class NetworkManager(PanopticonManager):
    _managed_obj_name = "panopticon"
    _manager_attribute_class = Network
    _selected_list = "selected_networks"
    _excluded_list = "excluded_networks"

