<?php

/**
 * 赛季状态
 */

namespace Framework\Model;

use Framework\Lib\Utils;
use Framework\Log\LogMark;
use Framework\Logic\CommonDataLogic;
use Framework\Logic\CommonTimerLogic;
use Framework\Logic\TemplateHelp;
use Game\Constant\ConstTemplate\TemplateMatchTime;
use Game\Constant\GameConstantDefine;
use Game\Constant\GameErrorCode;
use Game\Constant\ModelTypeDefine;
use Game\Constant\TemplateDefine;
use Game\Logic\CommonConstLogic;

class CommonSeasonStatusModel
{
    use CommonDataLogic;
    use CommonTimerLogic;
    use CommonConstLogic;
    use TemplateHelp;

    //设置赛季状态
    public function setSeasonStatus(int $seasonId): bool
    {
        $seasonConfigData = $this->getTitle(TemplateDefine::TYPE_MATCH_TIME, $seasonId);
        if (is_null($seasonConfigData)) {
            LogMark::getInstance()->markError(
                GameErrorCode::COMMON_SEASON_TIME_ERROR,
                "[CommonSeasonStatusModel] not found Season Config",
                array(
                    "seasonId" => $seasonId
                )
            );
            //关闭赛季
            $this->addCommonData($this->getPlayerModel(), GameConstantDefine::SEASON_STATUS_CLOSE);
            $data = array(
                GameConstantDefine::COMMON_KEY_SEASON_STATUS => GameConstantDefine::SEASON_STATUS_CLOSE
            );
            $this->saveCommonConstData($data);
            return false;
        }
        //检查状态
        $now = Utils::getServerTimestamp();
        if ($now >= $seasonConfigData[TemplateMatchTime::StartTime] && $now < $seasonConfigData[TemplateMatchTime::EndTime]) {
            $status = GameConstantDefine::SEASON_STATUS_OPEN;
        } else {
            $status = GameConstantDefine::SEASON_STATUS_CLOSE;
            //查找开启时间
            if ($now < $seasonConfigData[TemplateMatchTime::StartTime]) {
                //设置过期时间,加1秒防止卡时间检查状态未变化
                $this->addCommonTimer($this->getExpireModel(), 0, $seasonConfigData[TemplateMatchTime::StartTime] + 1);
            }
        }
        //修改赛季状态
        $this->addCommonData($this->getPlayerModel(), $status);
        $data = array(
            GameConstantDefine::COMMON_KEY_SEASON_STATUS => $status
        );
        $this->saveCommonConstData($data);
        return true;
    }

    //更新赛季状态
    public function commonTimerExpire(array $expireData): bool
    {
        if(empty($expireData)) {
            LogMark::getInstance()->markError(
                GameErrorCode::COMMON_TIMER_EXPIRE_DATA_ERROR,
                '[CommonSeasonStatusModel] timerExpire array empty!');
            return false;
        }
        //获取当前赛季Id
        $seasonId = $this->getCommonValueByModel(ModelTypeDefine::SEASON);
        return $this->setSeasonStatus($seasonId);
    }


    //玩家赛季model
    private function getPlayerModel(): int
    {
        return ModelTypeDefine::SEASON_STATUS;
    }

    //过期时间添加
    private function getExpireModel(): int
    {
        return ModelTypeDefine::COMMON_SEASON_STATUS;
    }
}
