generate Php;

namespace services;

class PollService {
	singleton;

	lazy String db_hostname;
	lazy String db_username;
	lazy String db_password;
	lazy Integer idElection;
	lazy Integer idpoll;
	lazy String allPolls;
	lazy String latestResult;

	ServiceProvidingCycle {
		Idle {
			getElectionPolls -> ElectionPollsLoaded;
			openPoll -> PollOpened;
		}
		ElectionPollsLoaded {
			entry / {$this->loadElectionPolls($this->db_hostname,$this->db_username,$this->db_password,$this->idElection);}
		}
		PollOpened {
			entry / {$this->tryToOpenPoll($this->db_hostname,$this->db_username,$this->db_password,$this->idpoll);}
		}
	}

	public function loadElectionPolls($db_hostname,$db_username,$db_password,$idElection) {
		$isConnected = mysql_connect($db_hostname,$db_username,$db_password);
		
		$result = mysql_query("SELECT * FROM elections.election where id_election=$idElection");

		require_once("./domain/Election.php");
		$anElection=null;
		
		while($row = mysql_fetch_array($result)) {
			$anElection=new Election($row['id_election'],$row['name'],$row['description']);
		}
		
  		$result = mysql_query("SELECT * FROM elections.poll where election_id_election=$idElection");

		require_once("./domain/Poll.php");
		
		$this->allPolls='{"polls" : [';
		$first=true;
		while($row = mysql_fetch_array($result)) {
			$aPoll=new Poll($row['id_poll'],$row['name'],$row['description'],$anElection);
			if ($first) {
				$this->allPolls=$this->allPolls.$this->jsonSerialize($aPoll);
				$first=false;
			} else
				$this->allPolls=$this->allPolls.",".$this->jsonSerialize($aPoll);
		}
		$this->allPolls=$this->allPolls.']}';

		mysql_close($isConnected);
	}
	
	public function tryToOpenPoll($db_hostname,$db_username,$db_password,$idpoll) {
		$isConnected = mysql_connect($db_hostname,$db_username,$db_password);
		
		$wasUpdated=false;
		if ($isConnected) {
			$wasUpdated = mysql_query("update elections.poll set status='open' where id_poll=$idpoll");
		}
		
		if ($isConnected && $wasUpdated)
			$this->latestResult='Poll open!';
		else
			$this->latestResult='An error occured!';
	}
	
	private function jsonSerialize($aPoll) {
		return '{"idpoll":"'.$aPoll->getIdPoll().'","name":"'.$aPoll->getName().'","description":"'.$aPoll->getDescription().'","theElection":"'.$aPoll->getElection()->getIdElection().'"}';
	}
}