<?php
Yii::import("application.library.IDN");

class CalculationForm extends CFormModel {
	public $domain; // xn-domain
	public $ip;
	public $idn; // президент.рф (IDN)
	private $_website;

	public function rules() {
		return array(
			array('domain', 'filter', 'filter'=>array('Helper', 'trimDomain')),
			array('domain', 'filter', 'filter'=>array($this, 'punycode')),
			array('domain', 'required'),
			array('domain', 'match', 'pattern' => '#^[a-z\d-]{1,64}\.[a-z\d-]{1,64}(.[a-z\d-]{1,64})*$#i'),
			array('domain', 'isReachable'),
			array('domain', 'tryToAnalyse'),
		);
	}

	public function punycode($domain) {
		$idn=new IDN;
		$this->domain=$idn->encode($domain);
		$this->idn=$idn->decode($domain);
		return $this->domain;
	}

	public function attributeLabels() {
		return array(
			'domain' => Yii::t("website", "Domain name"),
		);
	}

	public function isReachable() {
		if(!$this -> hasErrors()) {
			$this -> ip = gethostbyname($this -> domain);
			$long = ip2long($this -> ip);
			if($long == -1 OR $long === FALSE) {
				$this->addError("domain", Yii::t("website", "Could not reach host: {Host}", array("{Host}" => $this -> domain)));
			}
		}
	}

	public function getWebsite() {
		return $this->_website;
	}

	public function tryToAnalyse() {
		if(!$this -> hasErrors()) {
			$this->loadWebsite();
			// If website exists and we do not need to update data then exit from method
			if($this->_website AND ($notUpd = (strtotime($this->_website->modified_at) + Yii::app() -> params["webdataCache"] > time()))) {
				return true;
			} elseif($this->_website AND !$notUpd) {
				$args = array('yiic', 'calculate', 'update',
					"--domain={$this->domain}",
					"--idn={$this->idn}",
					"--ip={$this->ip}",
					"--wid={$this->_website->id}"
			);
			} else {
				$args = array('yiic', 'calculate', 'insert',
					"--domain={$this->domain}",
					"--idn={$this->idn}",
					"--ip={$this->ip}"
				);
			}

			// Get command path
			$commandPath = Yii::app() -> getBasePath() . DIRECTORY_SEPARATOR . 'commands';

			// Create new console command runner
			$runner = new CConsoleCommandRunner();

			// Adding commands
			$runner -> addCommands($commandPath);

			// If something goes wrong return error
			if($error = $runner -> run ($args)) {
				$this -> addError("domain", Yii::t("error_code", "Calculation Error Code $error"));
			} else {
				$this->loadWebsite();
				return true;
			}
		}
	}

	protected function loadWebsite() {
		if(!empty($this->_website)) {
			return;
		}
		$this->_website = Website::model()->findByAttributes(array(
			'md5domain'=>md5($this->domain),
		));
	}
}