<?php
class Create extends CAction
{
	public function run()
	{
		// Get the controller
		$controller = $this -> getController();

		// Get subscriber's id
		$subid = $controller -> subscriber -> id;

		// Get publisher's id
		$pubid = $controller -> publisher -> id;

		// Initialize room model
		$roomModel = new RoomModel();

		// Find room by attributes
		$room = $roomModel -> room(
			$pubid, $subid
		) -> find();

		// Initialize open tok library
		$opentok = new OpenTokSDK(API_Config::API_KEY, API_Config::API_SECRET);

		/*if($room AND $room -> sessionid != $controller -> publisher -> id) {
			$controller -> redirect($controller -> createUrl("room/join", array("id" => $subid)));
		} else if($room AND $room -> sessionid == $controller -> publisher -> id) {*/
		if($room) {
			$OpenTokID = $room -> opentok_id;
			$roomID = $room -> id;
		} else {
			$session = $opentok -> createSession($controller -> ip, array(SessionPropertyConstants::P2P_PREFERENCE=> "enabled"));
			$OpenTokID = $session->getSessionId();

			$roomModel -> sessionid = $pubid;
			$roomModel -> to_sessionid = $subid;
			$roomModel -> opentok_id = $OpenTokID;

			$roomModel -> save();
			$roomID = $roomModel -> id;
		}

		$informer = new InformerModel();

		$inform = $informer -> issetInform($pubid, $subid) -> count();
		if(!$inform) {
			$informer -> sessionid = $pubid;
			$informer -> to_sessionid = $subid;
			$informer -> save();
		}

		$data = array(
			'name' => $controller -> publisher -> name,
		);

		$token = $opentok -> generateToken($OpenTokID, RoleConstants::PUBLISHER, Yii::app() -> params['tokenTime'], json_encode($data));

		$controller -> render("index", array(
			"publisher" => $controller -> publisher,
			"subscriber" => $controller -> subscriber,
			"token" => $token,
			"opentokid" => $OpenTokID,
			"roomid" => $roomID,
		));
	}
}