<?php


/**
 * 聊天主逻辑
 * 主要是处理 onMessage
 */
use GatewayWorker\Lib\Gateway;
use Workerman\Lib\Timer;

class Events
{
    public static function onWorkerStart($businessWorker)
    {
        if ($businessWorker->id === 0) {
            Timer::add(3, function() {
                static $snapshot = [];
                $all_groups = Gateway::getAllGroupIdList();
                $groups_added = array_diff($all_groups, $snapshot);
                $groups_deleted = array_diff($snapshot, $all_groups);
                $snapshot = $all_groups;
                $online_uids = $offline_uids = [];
                foreach ($groups_added as $group) {
                    if (strpos($group, 'user-') === 0) {
                        $online_uids[] = (int)substr($group, 5);
                    }
                }
                foreach ($groups_deleted as $group) {
                    if (strpos($group, 'user-') === 0) {
                        $offline_uids[] = (int)substr($group, 5);
                    }
                }

                if (!$online_uids && !$offline_uids) {
                    return;
                }
                $config = include __DIR__ . '/../config.php';
                try {
                    $pdo = new PDO("mysql:dbname={$config['database']};host={$config['hostname']};port={$config['hostport']}", $config['username'], $config['password']);
                    if ($online_uids) {
                        $sql = "update user set state='online' where uid in (" .implode(',', $online_uids). ")";
                        echo $sql."\n";
                        $pdo->exec($sql);
                    }
                    if ($offline_uids) {
                        $sql = "update user set state='offline' where uid in (" .implode(',', $offline_uids). ")";
                        echo $sql."\n";
                        $pdo->exec($sql);

                    }
                } catch (PDOException $e) {
                    echo $e;
                }
            });
        }
    }

   public static function onWebsocketConnect($client_id, $data)
   {

   }
   
   /**
    * 有消息时
    * @param string $client_id
    * @param string $data
    */
   public static function onMessage($client_id, $data)
   {
        // 心跳
        if ($data == '1') {
            return;
        }

        // 客户端传递的是json数据
       $message = json_decode($data, true);
        if(!$message || !isset($message[0]) || !isset($message[1]))
        {
            return;
        }

        $type = $message[0];

        switch($type)
        {
            case 'sub':
                $groups = $message[1];
                if (!is_array($groups)) {
                    echo "bad subscribe message:$message\n";
                    return;
                }
                foreach ($groups as $group) {
                    if (is_scalar($group)) {
                        Gateway::joinGroup($client_id, $group);
                    }
                }
                Gateway::sendToClient($client_id, json_encode(['ok', $groups]));
                return;
            case 'unsub':
                $groups = $message[1];
                if (!is_array($groups)) {
                    echo "bad subscribe message:$message\n";
                    return;
                }
                foreach ($groups as $group) {
                    if (is_scalar($group)) {
                        Gateway::leaveGroup($client_id, $group);
                    }
                }
                return;
            default:
                echo "bad data $data\n";
                Gateway::closeClient($client_id);

        }
   }

}
