<?php

/**
 * TimerModel.php
 * 文件描述
 * Created On 2022/1/25
 * @author yuanb yuanbo0x@gmail.com
 */

namespace Framework\Model;

use Framework\Log\LogMark;
use Framework\DB\Handler\PlayerDBHandler;
use Game\Constant\DBTableDefine;

class TimerModel
{
    use PlayerDBHandler;

    public int $playerId;

    public function setPlayerId($playerId)
    {
        $this->playerId = $playerId;
    }

    public function getModelType(): int
    {
        return DBTableDefine::TABLE_TIMER;
    }

    public function addTimer($model, $titleId, $time, int $playerId): bool
    {
        $key = $model . "-" . $titleId;
        if ($playerId == 0) {
            return $this->addRank(
                DBTableDefine::TABLE_TIMER,
                $this->playerId,
                $key,
                $time
            );
        }
        return $this->addRank(
            DBTableDefine::TABLE_TIMER,
            $playerId,
            $key,
            $time
        );
    }

    public function delTimer($model, $titleId): bool
    {
        LogMark::getInstance()->markDebug(
            "timeout of del",
            array(
                'model' => $model,
                'titleId' => $titleId
            )
        );
        $key = $model . "-" . $titleId;
        return $this->delRank(DBTableDefine::TABLE_TIMER, $this->playerId, $key);
    }

    public function searchExpire($time): ?array
    {
        $expireData = array();
        $arr = array();
        if (false == $this->searchRank(DBTableDefine::TABLE_TIMER, $this->playerId, 0, $time, $arr)) {
            return null;
        }
        foreach ($arr as $k => $t) {
            $tmp = explode("-", $k);
            if (!is_array($tmp) || count($tmp) != 2) {
                // to do mark log
                continue;
            }
            $model = $tmp[0];
            $titleId = $tmp[1];
            if (!array_key_exists($model, $expireData)) {
                $expireData[$model] = array($titleId => $t);
            } else {
                $expireData[$model][$titleId] = $t;
            }
            $this->delTimer($model, $titleId);
        }
        return $expireData;
    }
}
