<?php

class RuCenterRequest extends RuCenterMessage
{
	
	public function generate()
	{
		$out = "";
		foreach ($this->getHeader()->getParameters() as $parameter) {
			foreach ($parameter->getValues() as $value) {
				$out .= $parameter->getName() . ": " . $value . self::CRLF;
			}
		}
		$out .= self::CRLF;
		if ($this->getBody()->hasParameters()) {
			foreach ($this->getBody()->getParameters() as $parameter) {
				foreach ($parameter->getValues() as $value) {
					$out .= $parameter->getName() . ": " . $value . self::LF;
				}
			}
			$out .= self::LF;
		}
		foreach ($this->getBody()->getSections() as $section) {
			$out .= "[" . $section->getName() . "]" . self::LF;
			foreach ($section->getParameters() as $parameter) {
				foreach ($parameter->getValues() as $value) {
					$out .= $parameter->getName() . ": " . $value . self::LF;
				}
			}
		}
		return $out;
	}
	
	public function send() {
		$input = $this->generate();
		
		dbg(__CLASS__ . "::" . __METHOD__ . "::[request]");
		dbg($input);
		
		$input = mb_convert_encoding($input, "koi8-r", "utf8");
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, RuCenterModule::REQUEST_URL);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_POSTFIELDS, array('SimpleRequest' =>  $input));
		curl_setopt($curl, CURLOPT_VERBOSE, true);
		
		$attemptsCount = 0;
		while (!($output = curl_exec($curl)) && $attemptsCount < RuCenterModule::REQUEST_ATTEMPTS_COUNT) {
			$attemptsCount++;
		}
		$output = mb_convert_encoding($output, "utf8", "koi8-r");
		curl_close($curl);

		dbg(__CLASS__ . "::" . __METHOD__ . "::[responce] | attempt: " . $attemptsCount);
		dbg($output);
		
		if (!$output) {
			throw new Exception("RuCenter sends empty responce [attempts count: " . RuCenterModule::REQUEST_ATTEMPTS_COUNT . "]");
		}
		
		return RuCenterResponce::load($output);
	}

}