<?php


class DictionaryForm extends CFormModel
{
	public $request;
	
	public $serverIsWorking;
	public $jsonString;
	public $response;
	

	public function rules()
	{
		return array(
			// username and password are required
			array('request', 'required', 'message'=>'{attribute} ' . Yii::t('app', 'Field should not be blank')),
		
		);
	}
	
	function attributeLabels(){
        return array(
			'request' => Yii::t('app', 'Please enter request:'),
        );
    }
	
	public function getResponse()
	{
		$this->serverIsWorking = false;
		$this->response = false;
	
		try
		{
			set_error_handler(function() { /* ignore errors */ });
			$this->jsonString = file_get_contents('http://127.0.0.1:8843/' . $this->request);
			$this->response = json_decode($this->jsonString, true);
			restore_error_handler();
			
			if ($this->jsonString)
			{
				$this->serverIsWorking = true;
			}
		}
		catch(Exception $ex)
		{
			$this->serverIsWorking = false;
		}	
		
		$this->serverIsWorking = true;
	}
	
	public function resultExists()
	{
		return ($this->serverIsWorking) && ($this->response) && ($this->response['words'] !== "");
	}
	
	public function getDataProvider()
	{
		$dataProvider=new CArrayDataProvider($this->response['words'], array(
			'id'=>'dictionaryResultDataProvider',
			'pagination'=>array(
				'pageSize'=>10,
			),
		));
		
		return $dataProvider;
	}
}
