<?php

/**
 * 玩家模块索引数据
 * key为对应modelId
 * value为索引值
 */

namespace Game\Data;

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

class SyncData
{
    use PlayerDBHandler;

    public const SYNC_TIME = "syncTime";    //上次同步时间

    public int $syncTime;
    public int $playerId;
    private int $id;

    public function __construct(int $playerId)
    {
        $this->playerId = $playerId;
        $this->syncTime = 0;
    }

    public function getData($id = 0): bool
    {
        $this->id = $id;
        $result = array();
        if (!$this->searchTitle(
            DBTableDefine::TABLE_ACCOUNT,
            $this->playerId,
            $this->id,
            $result)
        ) {
            return false;
        }
        $this->formatData($result);
        return true;
    }

    public function saveDB(): bool
    {
        $data = array();
        foreach ($this as $k => $v) {
            if (is_numeric($k)) {
                $data[$k] = $v;
            } elseif ($k == self::SYNC_TIME) {
                $data[self::SYNC_TIME] = $v;
            }
        }
        if(!$this->updateTitle(DBTableDefine::TABLE_ACCOUNT, $this->playerId, $this->id, $data)) {
            LogMark::getInstance()->markWarn(GameErrorCode::DATA_UPDATE_ERROR,
                                              '[SyncData] update mail error!',
                                              $data);
            return false;
        }
        return true;
    }

    private function formatData($result)
    {
        foreach ($result as $key => $value) {
            if (is_numeric($key)) {
                $val = (int)$key;
                $this->$val = (int)$value;
            } elseif ($key == self::SYNC_TIME) {
                $this->syncTime = (int)$value;
            }
        }
    }
}
