<?php
namespace EmotionHero\Server;
use WebSocket\Client;

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Websockets implements MessageComponentInterface
{
	protected $clients;

    public static function triggerUpdate(string $type) {
        $client = new Client("ws://localhost:8181/");
        $client->send(json_encode(['action'=>'update', 'method'=>$type]));
        $client->receive(); 
        unset($client);
    }

    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
        // Store the new connection to send messages to later
        $this->clients->attach($conn);

        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        echo sprintf('Connection %d sending message "%s"' . "\n"
            , $from->resourceId, $msg);

        $data = @json_decode($msg, true);
        if(!empty($data) && $data['action'] == 'update' && isset($data['method'])) 
        {
            foreach ($this->clients as $client) {
                if ($from !== $client) {
                    // The sender is not the receiver, send to each client connected
                    $client->send(json_encode(['action'=>"update", 'method'=>$data['method']]));
                }
            }
        }
    }

    public function onClose(ConnectionInterface $conn) {
        // The connection is closed, remove it, as we can no longer send it messages
        $this->clients->detach($conn);

        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";

        $conn->close();
    }
}