<?php
/**
 * 在线模块
 * @date 2022-4-13
 * @author JZW
 **/


namespace Framework\Model;


use Framework\Lib\Utils;
use Framework\Log\LogMark;
use Framework\DB\Handler\CommonDBHandler;
use Game\Constant\DBTableDefine;
use Game\Constant\GameErrorCode;

class OnLineModel
{
    use CommonDBHandler;
    public const Interval = 40;
    public const BackGround = 1800; // 30分钟,超过这个时间重新登录
    public const OffLineDefaultTime = 0; // 离线后时间被归0

    public function getDBTable(): string
    {
        return DBTableDefine::TABLE_ONLINE;
    }

    public function updateOnLine($playerId, $time): bool
    {
        if (false == $this->addCommonRank(
                $this->getDBTable(),
                0,
                $playerId,
                $time
            )) {
            LogMark::getInstance()->markError(
                GameErrorCode::UPDATE_ON_LINE_ERROR,
                "[OnLineModel] add on-line timer error",
                array(
                    "playerId" => $playerId,
                    "time" => $time
                )
            );
            return false;
        }
        return true;
    }

    public function getOnLineTime($playerId, &$ret): bool
    {
        if (false == $this->searchRankScoreByKeyCommon(
                $this->getDBTable(),
                0,
                $playerId,
                $ret
            )) {
            LogMark::getInstance()->markError(
                GameErrorCode::SEARCH_ON_LINE_ERROR,
                "[OnLineModel] search on-line timer error",
                array(
                    "playerId" => $playerId,
                )
            );
            return false;
        }
        return true;
    }

    //获取当前在线的玩家
    public function getOnLineBySore(&$ret): bool
    {
        $now = Utils::getServerTimestamp();
        $start = $now - self::Interval+1;
        $end = $now + self::Interval;
        if (false === $this->searchCommonRank(
            $this->getDBTable(),
                0,
                $start,
                $end,
                $ret
            )){
            LogMark::getInstance()->markError(
                GameErrorCode::SEARCH_ON_LINE_ERROR,
                "[OnLineModel] search on-line error",
            );
            return false;
        }
        return true;
    }

    //获取当前离线但未处理的玩家
    public function getOffLineBySore(&$ret): bool
    {
        $now = Utils::getServerTimestamp();
        $start = 1;
        $end = $now - self::Interval;
        if (false === $this->searchCommonRank(
                $this->getDBTable(),
                0,
                $start,
                $end,
                $ret
            )){
            LogMark::getInstance()->markError(
                GameErrorCode::SEARCH_ON_LINE_ERROR,
                "[OnLineModel] search off-line error",
            );
            return false;
        }
        return true;
    }
}