<?php

/**
 * 总熟练度
 */

namespace Game\Data;

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

class ProficiencyData
{
    use PlayerDBHandler;

    public int $playerId;

    public const PROFICIENCY_LV = "ProficiencyLv";      //熟练度等级
    public const PROFICIENCY_REWARD = "ProficiencyReward";                  //普通熟练度奖励进度[奖励id,..]
    public const PROFICIENCY_EXPERT_REWARD = "ProficiencyExpertReward";     //高级熟练度奖励进度[奖励id,..]
    public const PROFICIENCY_FLAG = "ProficiencyFlag";     //高阶开通标志

    public const DB_KEY_MAP = array(
        self::PROFICIENCY_LV => "proficiencyLv",
        self::PROFICIENCY_REWARD => "proficiencyReward",
        self::PROFICIENCY_EXPERT_REWARD => "proficiencyExpertReward",
        self::PROFICIENCY_FLAG => "proficiencyFlag",
    );

    public int $proficiencyLv;
    public string $proficiencyReward;
    public string $proficiencyExpertReward;
    public bool $proficiencyFlag;
    private bool $isLoad = false;

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

    public function initProficiencyData()
    {
        $this->proficiencyLv = 0;
        $this->proficiencyReward = "[]";
        $this->proficiencyExpertReward = "[]";
        $this->proficiencyFlag = false;
        $this->isLoad = true;
        $this->updateDB();
    }

    public function updateDB(): bool
    {
        $data = array();
        foreach (self::DB_KEY_MAP as $k => $v) {
            if ($k == self::PROFICIENCY_FLAG) {
                $data[$k] = (int)$this->$v;
            } else {
                $data[$k] = $this->$v;
            }
        }
        return $this->updateTitle(
            DBTableDefine::TABLE_ACCOUNT,
            $this->playerId,
            0,
            $data
        );
    }

    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);
        }
        if (!$this->isLoad) {
            return false;
        }
        return true;
    }

    private function setDBData($key, $value)
    {
        if (!array_key_exists($key, self::DB_KEY_MAP)) {
            return;
        }
        $this->isLoad = true;
        $property = self::DB_KEY_MAP[$key];
        if ($key == self::PROFICIENCY_FLAG) {
            $this->proficiencyFlag = (bool)(int)$value;
        } elseif ($key == self::PROFICIENCY_LV) {
            $this->proficiencyLv = (int)$value;
        } else {
            $this->$property = $value;
        }
    }
}
