<?php
class WizardStepProxySettings extends WizardStep
{
    protected function run()
    {
        
        
        $formModel = new ProxySettingsForm();
        $this->setDefaultProxyConfiguration($formModel);
        $this->performAjaxValidation($formModel, "proxy-settingst-form");
        
        if (isset($_POST["ProxySettingsForm"])) {
            $formModel->attributes = $_POST["ProxySettingsForm"];
            $this->configureProxy($formModel);
            
            $this->setStepIsDone(true);
            return;
            
            /* FIXME: need this as ajax call or something ...
            if ($this->checkAPIConnection($formModel)) {
                $this->setStepIsDone(true);
                return;
            }
            */
        }
        $this->wizardController->render("proxySettings", array("formModel" =>$formModel));
    }
    
    private function setDefaultProxyConfiguration(&$formModel)
    {
        $formModel->httpProxy = cfg('HTTP_PROXY_IP_ADDRESS');
        $formModel->httpProxyPort = cfg('HTTP_PROXY_PORT');
        $formModel->httpProxyUser = cfg('HTTP_PROXY_USERNAME');
        $formModel->httpProxyPassword = cfg('HTTP_PROXY_PASSWORD');
        
        $formModel->httpsProxy = cfg('HTTPS_PROXY_IP_ADDRESS');
        $formModel->httpsProxyPort = cfg('HTTPS_PROXY_PORT');
        $formModel->httpsProxyUser = cfg('HTTPS_PROXY_USERNAME');
        $formModel->httpsProxyPassword = cfg('HTTPS_PROXY_PASSWORD');
    }
    
    private function configureProxy($formModel) 
    {
        setCfg('HTTP_PROXY_IP_ADDRESS', $formModel->httpProxy);
        setCfg('HTTP_PROXY_PORT', $formModel->httpProxyPort);
        setCfg('HTTP_PROXY_USERNAME', $formModel->httpProxyUser);
        setCfg('HTTP_PROXY_PASSWORD', $formModel->httpProxyPassword);
        setCfg('HTTPS_PROXY_IP_ADDRESS', $formModel->httpProxy);
        setCfg('HTTPS_PROXY_PORT', $formModel->httpsProxyPort);
        setCfg('HTTPS_PROXY_USERNAME', $formModel->httpsProxyUser);
        setCfg('HTTPS_PROXY_PASSWORD', $formModel->httpsProxyPassword);
    }
    
    private function checkAPIConnection($model)
    {
        $result = LicenseServer::checkConnection();

        if ($result === true) {
            return true;
        }

        Yii::app()->user->setFlash('error', "<strong>Error " . $result['httpCode'] . ": </strong>" . $result['errmsg'] . '<br><br>');
        return false;
    }
}