# -*- coding: utf-8 -*-

# Copyright 2008-2016 Mir Calculate. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import socket
from ..datavars import ReadonlyVariable
from ..utils import ip


class VariableOsNetHostname(ReadonlyVariable):
    """
    Hostname
    """

    def get(self):
        return self.Get('os_net_fqdn').partition('.')[0]


class VariableOsNetDomain(ReadonlyVariable):
    """
    Domain name
    """

    def get(self):
        return self.Get('os_net_fqdn').partition('.')[2]


class VariableOsNetFqdn(ReadonlyVariable):
    """
    Full qualited domain name
    """

    def get(self):
        fqdn = socket.getfqdn()
        if not fqdn:
            fqdn = "calculate"
        if "." not in fqdn:
            return "%s.local" % fqdn
        else:
            return fqdn


class VariableOsNetAllow(ReadonlyVariable):
    """
    Allowed networks (comma delimeter)
    """

    def get(self):
        """Allowed networks"""
        networks = []
        net_interfaces = self.Get("os_net_interfaces")
        for i in net_interfaces:
            iface = ip.getMaster(i) or i
            ipaddr, mask = ip.getIp(iface), ip.cidrToMask(ip.getMask(iface))
            if ipaddr and mask:
                networks.append(ip.getIpNet(ipaddr, mask))
        return ",".join(list(set((x for x in networks if x))))


class VariableOsNetIp(ReadonlyVariable):
    """
    IP for all network interfaces (comma delimeter)
    """

    def get(self):
        """All computer ip addresses, comma delimeter"""
        ips = []
        net_interfaces = self.Get("os_net_interfaces")
        for i in net_interfaces:
            iface = ip.getMaster(i) or i
            ipaddr = ip.getIp(iface)
            if ipaddr:
                ips.append(ipaddr)
        return ",".join(list(set(ips)))


class VariableOsNetInterfaces(ReadonlyVariable):
    """
    Network interfaces
    """
    type = "list"

    def get(self):
        """All net interfaces"""
        return ip.getInterfaces()
