<?php

class NetworkInterface extends PhonalisaRecord
{

    public $ip;
    public $netmask;
    public $subnet;
    public $name;
    public $isPrimary;
    public $dns;
    public $gateway;
    public $mac = '';

    public static function myAttributes()
    {
        return array(
            "ip" => "ip",
            "netmask" => "netmask",
            "subnet" => "subnet",
            "name" => "name",
            'isPrimary' => 'isPrimary',
            'dns' => 'dns',
            'gateway' => 'gateway',
            'mac' => 'mac'
        );
    }

    public function rules()
    {
        return array(
            array("ip, netmask, subnet, name, isPrimary, dns, gateway, mac", "safe"), //FIXME ? 
            array('ip, netmask, subnet, name, isPrimary, dns, gateway, mac', 'safe', 'on' => 'search')
        );
    }

    public function attributeLabels()
    {
        return array(
            "ip" => __("NETWORK_INTERFACE_MODEL_IP"),
            "netmask" => __("NETWORK_INTERFACE_MODEL_NETMASK"),
            "subnet" => __("NETWORK_INTERFACE_MODEL_SUBNET"),
            "name" => __("NETWORK_INTERFACE_MODEL_NAME"),
            "isPrimary" => __("NETWORK_INTERFACE_MODEL_IS_PRIMARY"),
            "dns" => __("NETWORK_INTERFACE_MODEL_DNS"),
            "gateway" => __("NETWORK_INTERFACE_MODEL_GATEWAY"),
        );
    }

    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    public function search($order = 'name')
    {
        $criteria = new CDbCriteria;
        $filter = $this->getFilter($criteria, $order);

        $filter['pagination'] = array(
            'pageSize' => getGridPageSize('calendar-grid'),
        );

        if ($filter != null) {
            return new CPhonalisaDataProvider($this, array(
                'criteria' => $criteria,
            ));
        }
    }

    public static function getListData()
    {
        $models = self::model()->findAll();
        $lData = array();
        foreach ($models as $model) {
            $lData[$model->ip] = $model->name . ": " . $model->ip . "/" . $model->concertedNetmask();
        }
        return $lData;
    }

    public function concertedNetmask()
    {
        $bits = 0;
        $netmask = explode(".", $this->netmask);

        foreach ($netmask as $octect) {
            $bits += strlen(str_replace("0", "", decbin($octect)));
        }
        return $bits;
    }

    public function getIpAsCIDR()
    {
        $cidr = $this->concertedNetmask();
        $subnet = long2ip((ip2long($this->ip) & ~((1 << (32 - $cidr)) - 1)));
        return $subnet . "/" . $this->concertedNetmask();
    }

    public function getBroadcast()
    {
        $ip_int = ip2long($this->ip);
        $netmask_int = ip2long($this->netmask);
        $broadcast_int = $ip_int | (~ $netmask_int);
        return long2ip($broadcast_int);
    }

    public function cidrToRange()
    {
        $range = array();
        $subnet = $this->subnet;
        if (empty($subnet)) {
            $subnet = $this->getIpAsCIDR();
        }

        $range[0] = long2ip(ip2long($this->ip) + 1);
        $range[1] = long2ip(ip2long($this->broadcast) - 1);

        return $range;
    }

    public function beforeSave()
    {
        if ($this->isPrimary == '1') {
            $oldModel = NetworkInterface::model()->findByAttributes(array('isPrimary' => '1'));
            if ($oldModel && $this->id !== $oldModel->id) {
                $oldModel->isPrimary = '0';
                $oldModel->save();
            }
        }
        return parent::beforeSave();
    }

    public function afterSave()
    {
        if ($this->isPrimary == '1' && $this->scenario != 'wizard') {

            $oldIP = cfg('PROV_HOST');
            $newIP = $this->ip;
            setCfg('PROV_HOST', $newIP);

            if (cfg('NTP_HOST') === $oldIP) {
                setCfg('NTP_HOST', $newIP);
            }
            if (cfg('SIP_HOST') === $oldIP) {
                setCfg('SIP_HOST', $newIP);
            }
            setCfg('PROV_INIT_FROM_NET', $this->getIpAsCIDR());
        }
        return parent::afterSave();
    }

    public function getHumandReadablePrimaryStatus($isPrimary)
    {
        $icon = 'remove';
        if (!empty($isPrimary)) {
            $icon = 'ok';
        }
        return "<i class='icon-$icon icon-1x'></i>";
    }

    public function changeDhcpWithPrimaryNetworkAdapterSettings()
    {
        $range = $this->cidrToRange();
        $networkSettings = array();
        $networkSettings['GLOBAL_SUBNET_MASK'] = $this->netmask;
        $networkSettings['GLOBAL_SUBNET'] = $this->getIpAsCIDR();
        $networkSettings['GLOBAL_BROADCAST_ADDRESS'] = $this->getBroadcast();
        $networkSettings['GLOBAL_ROUTER'] = $this->gateway;
        $networkSettings['GLOBAL_DNS'] = $this->dns;
        $networkSettings['GLOBAL_NTP'] = cfg('NTP_HOST');
        $networkSettings['RANGE_FROM'] = $range[0];
        $networkSettings['RANGE_TO'] = $range[1];

        foreach ($networkSettings as $key => $postAttributes) {
            $model = NetworkSettings::model()->findByAttributes(array('key' => $key));
            if ($model == NULL) {
                $model = new NetworkSettings();
            }
            $model->key = $key;
            $model->value = trim($postAttributes);
            if (!$model->save()) {
                return false;
            }
        }
        return true;
    }

    public static function writeNetworkConfigsToCtrld()
    {
        $result = false;
        $models = NetworkInterface::model()->findAll();
        $data = array();
        foreach ($models as $model) {
            $data[$model->name] = $model->attributes;
        }
        $ctrldCMD = PhonalisaCtrldConnector::writeNetworkConfig($data);
        if (isset($ctrldCMD->status) && $ctrldCMD->status == 'ok') {
            $result = true;
        }
        return $result;
    }

    public static function getMacAddress()
    {
        $mac = '';
        $networkInterface = NetworkInterface::model()->findByAttributes(array('isPrimary' => '1'));
        if ($networkInterface) {
            $mac = $networkInterface->mac;
        } else {
            $networkInterfaces = NetworkInterface::model()->findAll();
            foreach($networkInterfaces as $interface) {
                if(!empty($interface->ip) && !empty($interface->netmask) && !empty($interface->subnet)) {
                    $mac = $interface->mac;
                    break;
                }
            }
        }
        return $mac;
    }
}
