<?php

/**
 * 玩家模块索引数据
 */

namespace Game\Model;

use Framework\Lib\Utils;
use Framework\Logic\CommonDataLogic;
use Framework\MVC\ModelManager;
use Game\Data\SyncData;

class SyncModel
{
    use CommonDataLogic;

    public int $playerId;

    private ?SyncData $data = null;

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

    public function getLastSyncTime(): int
    {
        if ($this->init() == false) {
            return 0;
        }
        return $this->data->syncTime;
    }

    public function getPlayerModelIndexList(): ?SyncData
    {
        if ($this->init() == false) {
            return null;
        }
        return $this->data;
    }

    //更新模块索引
    public function updatePlayerModelIndex($key, $value)
    {
        $this->data->$key = $value;
    }

    //更新同步时间
    public function updateLastSyncTime()
    {
        $this->data->syncTime = Utils::getServerTimestamp();
    }

    public function savePlayerModelIndex(): bool
    {
        return $this->data->saveDB();
    }

    //同步系统模块
    public function syncSysModel()
    {
        //获取系统模块
        $commonModelIndexList = $this->getCommonData();
        $playerModelIndexList = $this->getPlayerModelIndexList();
        foreach ($commonModelIndexList as $modelType => $index) {
            //检查玩家是否存在对应模块
            $playerIndex = property_exists($playerModelIndexList, $modelType) ?
                $playerModelIndexList->$modelType : 0;
            //索引比较处理
            if ($index != $playerIndex) {
                //索引不一致 通知对应model更新
                $model = ModelManager::getInstance()->getModel($modelType);
                if (method_exists($model, "syncCommonData")) {
                    $model->syncCommonData($playerIndex, $index);
                }
                //更新玩家模块索引
                $this->updatePlayerModelIndex($modelType, $index);
            }
        }
    }


    private function init(): bool
    {
        if ($this->data != null) {
            return true;
        }
        $this->data = new SyncData($this->playerId);
        if ($this->data->getData()) {
            return true;
        }
        unset($this->data);
        $this->data = null;
        return  false;
    }
}
