<?php

/**
 * 大乱斗玩家信息
 */

namespace Game\Data\Activity;

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

class ScuffleData
{
    use PlayerDBHandler;

    public int $playerId;

    private int $initScore;

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

    public const SCUFFLE_ROLL_POINT = "ScuffleRollPoint";   //骰子点数
    public const SCUFFLE_SCORE = "ScuffleScore";            //大乱斗积分
    public const SCUFFLE_USE_CAR = "ScuffleUseCar";         //大乱斗活动,使用过的车 json [carId,..]
    public const SCUFFLE_DAILY_WIN = "ScuffleDailyWin";     //大乱斗每日首胜

    public const DB_KEY_MAP = array(
        self::SCUFFLE_ROLL_POINT => "scuffleRollPoint",
        self::SCUFFLE_SCORE => "scuffleScore",
        self::SCUFFLE_USE_CAR => "scuffleUseCar",
        self::SCUFFLE_DAILY_WIN => "scuffleDailyWin",
    );

    public int $scuffleRollPoint = 0;
    public int $scuffleScore = self::DEFAULT_SCORE;    //初始积分
    public string $scuffleUseCar = "[]";
    public int $scuffleDailyWin = 0;

    public const DEFAULT_SCORE = 1000;

    public function initScuffleData()
    {
        $this->scuffleRollPoint = 0;
        $this->scuffleScore = self::DEFAULT_SCORE;
        $this->scuffleUseCar = "[]";
        $this->scuffleDailyWin = 0;
    }

    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 updateDB(): bool
    {
        $data = array();
        foreach (self::DB_KEY_MAP as $k => $v) {
            $data[$k] = $this->$v;
        }
        return $this->updateTitle(
            DBTableDefine::TABLE_ACCOUNT,
            $this->playerId,
            0,
            $data
        );
    }

    public function registerDB(): bool
    {
        $data = array();
        foreach (self::DB_KEY_MAP as $k => $v) {
            $data[$k] = $this->$v;
        }
        return PlayerDBPipe::getInstance()->createTitle(
            DBTableDefine::TABLE_ACCOUNT,
            $this->playerId,
            0,
            $data
        );
    }

    private 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 = (int)$value;
        } else {
            $this->$property = $value;
        }
    }
}
