<?php
require_once __DIR__ . '/vendor/autoload.php';
use Workerman\Worker;

// SSL context.
$context = array(
    'ssl' => array(
        'local_cert'  => '/etc/letsencrypt/live/online.vmajlis.uz/fullchain.pem',
        'local_pk'    => '/etc/letsencrypt/live/online.vmajlis.uz/privkey.pem',
        'verify_peer' => false,
    )
);

// массив для связи соединения пользователя и необходимого нам параметра
$users = [];
$GLOBALS["chTime"] = time();
$GLOBALS["users"] = [];
// Create a Websocket server
$ws_worker = new Worker("websocket://0.0.0.0:8085",$context);

// 4 processes
$ws_worker->count = 4;
$ws_worker->transport = 'ssl';

tLog( "-------- ======== WebSOCKET start on [0.0.0.0]:[8085] =========----------" );

$ws_worker->onWorkerStart = function() use (&$users) {
	
    // создаём локальный tcp-сервер, чтобы отправлять на него сообщения из кода нашего сайта
    $inner_tcp_worker = new Worker("tcp://127.0.0.1:12345");
    // создаём обработчик сообщений, который будет срабатывать,
    // когда на локальный tcp-сокет приходит сообщение
    $inner_tcp_worker->onMessage = function($connection, $data) use (&$users) {
		
		tLog( "onMessage: " . $data );
		
		$connection->send("Msg got by Server.");
		
        $data = json_decode($data,true);
		
        // отправляем сообщение пользователю по userId
        if (isset($GLOBALS["users"][$data->user])) {
            $webconnection = $GLOBALS["users"][$data->user];
            $webconnection->send($data->message);
        }
        /*if (isset($users[$data->user])) {
            $webconnection = $users[$data->user];
            $webconnection->send($data->message);
        }*/
		
		
    };
    $inner_tcp_worker->listen();
};


$ws_worker->onConnect = function($connection) use (&$users, $ws_worker) {

    $connection->onWebSocketConnect = function($connection) use (&$users, $ws_worker) {
		tLog( "onConnect: " . json_encode($_GET) );
		tLog( "onConnect_WSconn: " . $connection->id );
        //$users[$_GET['v']] = $connection;
        $GLOBALS["users"][$_GET['v']] = $connection;

        
		
		$myConnId =  $connection->id;
	
		/*  TEST connections */
		foreach($ws_worker->connections as $connection){
			tLog( "checkSEND: " . $connection->id );
			if(  $myConnId == $connection->id ){
				$connection->send("Wellcome: [".$_GET['v']."][".$GLOBALS["users"][$_GET['v']]->id."][".$myConnId."]");
			} else {
				$connection->send("NewConnect: [".$_GET['v']."][".$GLOBALS["users"][$_GET['v']]->id."][".$myConnId."]");
			}
			
		}
		
		
   };
};



// Emitted when connection Msg
$ws_worker->onMessage = function($connection, $data) use(&$users, $ws_worker)
{
	tLog( "onMessage_users: " . json_encode($GLOBALS["users"]) );
	tLog( "onMessage_DATA: " . $data );
    
	$arData = json_decode($data,true);
	tLog( "onMessage_VID: " . $arData['vid'] );
    if( isset($GLOBALS["users"][$arData['vid']]) ) {
		$connection->send("I know you!");
	} else {
		$connection->send("Who you!");
	}
		
};

// Emitted when connection closed
$ws_worker->onClose = function($connection) use(&$users)
{
	tLog( "onClose: " . json_encode($connection) );
    // удаляем параметр при отключении пользователя
    //$user = array_search($connection, $users);
    $user = array_search($connection, $GLOBALS["users"]);
    unset($GLOBALS["users"][$user]);
};

function tLog( $text ) {
	$logfile = __DIR__."/websocket.log";
	$nowdate = date("Y-m-d_H:i:s");
	file_put_contents($logfile, $nowdate."(".$GLOBALS["chTime"] .") [".$text."] \n", FILE_APPEND | LOCK_EX);
}

// Run worker
Worker::runAll();