<?php

/**
 * 赛季信息统计
 */

namespace Game\Model\Season;

use Framework\Log\LogMark;
use Game\Data\SeasonStatisticsData;

class SeasonStatisticsModel
{
    public int $playerId;

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

    /***
     * 注册时调用
     */
    public function onRegister()
    {
        $this->initSeasonStatistics(SeasonStatisticsData::TITLE_RANKING);
        $this->initSeasonStatistics(SeasonStatisticsData::TITLE_PRACTICE);
    }

    //初始数据
    private function getInitData(): array
    {
        $initData = array();
        foreach (SeasonStatisticsData::DB_KEY_MAP as $val) {
            $initData[$val] = 0;
        }
        return $initData;
    }

    //初始统计信息
    private function initSeasonStatistics(int $title, bool $isRegister = true)
    {
        $ssd = new SeasonStatisticsData($this->playerId);
        $ssd->setTitle($title);
        if ($isRegister) {
            $ssd->registerDB($this->getInitData());
        } else {
            $ssd->createDB($this->getInitData());
        }
    }

    //获取统计信息
    public function getSeasonStatistics(int $title): array
    {
        $ssd = new SeasonStatisticsData($this->playerId);
        $ssd->setTitle($title);
        $ssdData = $ssd->getDataFromDB();
        if (empty($ssdData)) {
            $this->initSeasonStatistics($title, false);
            $ssdData = $this->getInitData();
        }
        return $ssdData;
    }

    //重置赛季信息
    public function resetNowSeasonData()
    {
        LogMark::getInstance()->markDebug("[SeasonStatisticsModel] reset Season data");
        //重置排位赛数据
        $ssd = new SeasonStatisticsData($this->playerId);
        $ssd->setTitle(SeasonStatisticsData::TITLE_RANKING);
        $resetData = array();
        foreach (SeasonStatisticsData::NOW_SEASON_KEY as $key) {
            $resetData[$key] = 0;
        }
        $ssd->saveDB($resetData);
        //重置练习赛数据
        $ssd->setTitle(SeasonStatisticsData::TITLE_PRACTICE);
        $resetData = array();
        foreach (SeasonStatisticsData::NOW_SEASON_KEY as $key) {
            $resetData[$key] = 0;
        }
        $ssd->saveDB($resetData);
    }

    //保存
    public function saveSeasonStatistics(array $data, int $title)
    {
        $ssd = new SeasonStatisticsData($this->playerId);
        $ssd->setTitle($title);
        $ssd->saveDB($data);
    }

    //根据当前赛季key 找到对应全部赛季含义一致的key
    public function getSameKey(string $key): ?string
    {
        return SeasonStatisticsData::NOW_SEASON_TO_ALL_SEASON_KEY[$key] ?? null;
    }

}
