<?php

namespace Server\websocket;

use App\Services\HttpService;
use App\Services\MicroService;

class WebsocketService extends MicroService {

    public $uniacid = 0;
    public $authKey = "";
    public $settings = array(
        'type'=>'remote',
        'server'=>'wss://socket.whotalk.com.cn/wss',
        'api'=>'https://socket.whotalk.com.cn/api/message/sendMessageToUser'
    );

    function __construct($uniacid=null){
        parent::__construct('websocket');
        global $_W;
        if ($uniacid===null){
            $uniacid = $_W['uniacid'];
        }
        $this->uniacid = intval($uniacid);
        $this->authKey = env('APP_AUTHKEY','');
        $setting = $this->SettingLoad('swasocket');
        if (!empty($setting['swasocket'])){
            $this->settings = $setting['swasocket'];
        }
    }

    public function Send($message, $userIds, $fromId=0){
        global $_W;
        $data = array(
            'message'=>is_array($message)?json_encode($message):$message,
            'userIds'=>is_array($userIds)?implode(",", $userIds) : $userIds,
            'fromId'=>$fromId,
            'token'=>$_W['token'],
            'siteRoot'=>$_W['siteroot']
        );
        $res =  HttpService::ihttp_post($this->settings['api'], $data);
        if(is_error($res)) return $res;
        return json_decode($res['content'],true);
    }

    public function getKey($userId, $prefix=''){
        return md5($prefix.$this->authKey.':'.$this->uniacid.":$userId");
    }



}
