<?php

/***
 * JoinId
 */

namespace Game\Data;

use Framework\DB\Handler\PlayerDBHandler;
use Game\Constant\DBTableDefine;
use Game\Constant\GameConstantDefine;

class JoinIdData
{
    use PlayerDBHandler;

    public const JOIN_ID = "JoinId";
    public const STATUS = "Status"; //pvp状态

    public int $joinId = 0;
    public int $status = GameConstantDefine::PLAYER_STATUS_ONLINE;

    public int $playerId;

    public const DB_KEY_MAP = array(
        self::JOIN_ID => "joinId",
        self::STATUS => "status",
    );

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

    public function setDBData($key, $value)
    {
        if (!array_key_exists($key, self::DB_KEY_MAP)) {
            return;
        }
        $property = self::DB_KEY_MAP[$key];
        if (is_numeric($value)) {
            $this->$property = intval($value);
        } else {
            $this->$property = $value;
        }
    }

    public function searchDB(): bool
    {
        $result = array();
        if (!$this->searchTitle(
            DBTableDefine::TABLE_ACCOUNT,
            $this->playerId,
            0,
            $result)
        ) {
            return false;
        }
        if (empty($result)) {
            return false;
        }
        foreach ($result as $k => $v) {
            $this->setDBData($k, $v);
        }
        return true;
    }

    public function saveJoinId($id = 0): bool
    {
        if($id == 0) {
            $id = $this->playerId;
        }
        return $this->updateTitle(
            DBTableDefine::TABLE_ACCOUNT,
            $id,
            0,
            array(
                self::JOIN_ID => $this->joinId,
                self::STATUS => $this->status,
            )
        );
    }
}

