<?php

class WizardStepNetworkSettings extends WizardStep
{
    public function run()
    {   
        $defaultNetworkInterface = NetworkInterface::model()->findByAttributes(array());
        if (!$defaultNetworkInterface) {
            $defaultNetworkInterface = new NetworkInterface();
        }
        
        $formModel = new NetworkSettingsForm("networkSettings");
        $formModel->ip = $defaultNetworkInterface->ip;
        $formModel->subnetMask = $defaultNetworkInterface->netmask;
        
        $this->performAjaxValidation($formModel, 'network-settings-form');
        
        if (isset($_POST["NetworkSettingsForm"]))
        {   
            $formModel->attributes = $_POST["NetworkSettingsForm"];
            $this->setSystemConfig($formModel, $defaultNetworkInterface);
            $this->setStepIsDone(true);
            return;
        }
        
        $this->wizardController->render("networkSettings", array("formModel" => $formModel));
    }
    
    private function setSystemConfig($formModel, $networkInterface) 
    {
        setCfg('PROV_HOST', $formModel->ip);
        setCfg('SIP_HOST', $formModel->ip);
        setCfg('NTP_HOST', $formModel->ip);
        setCfg('PROV_PORT', $this->getProvPort());        
        setCfg('PROV_PORT_SECURE', $this->getProvPort(true));
        setCfg('PROV_INIT_FROM_NET', $networkInterface->getIpAsCIDR());
    }
    
    private function getProvPort($secure = false)
    {
        $port = $secure ? '443' : '80';
        
        $globalConfigDefault = Yii::app()->params->globalConfigDefault;
        if (!is_array($globalConfigDefault)) {
            return $port;
        }
        
        $settingsKey = $secure ? "PROV_PORT_SECURE" : "PROV_PORT";
        if (array_key_exists($settingsKey, $globalConfigDefault)) {
            $port = $globalConfigDefault[$settingsKey];
        }
        return $port;
    }
}