<?php

/**
 * 驾照考试关卡 试驾关卡 技巧教学关卡
 */

namespace Game\Data\PVE;

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

class LevelData
{
    use PlayerDBHandler;

    public int $playerId;

    public const LevelId = "LevelId";   //关卡id
    public const Status = "Status"; //关卡状态 0进行中 1已完成 2关闭(剧情支线)
    public const Target = "Target"; //目标完成状态 x-x-x x=0未完成 1已完成
    public const RewardStatus = "RewardStatus"; //奖励领取状态 x-x-x x=0不可领取 1可领取 2已领取

    public const DB_KEY_MAP = array(
        self::LevelId => "levelId",
        self::Status => "status",
        self::Target => "target",
        self::RewardStatus => "rewardStatus"
    );

    public int $levelId;
    public int $status;
    public string $target;
    public string $rewardStatus;

    //关卡状态
    public const STATUS_DOING = 0;
    public const STATUS_OVER = 1;
    public const STATUS_CLOSE = 2;

    //目标状态
    public const TARGET_STATUS_DOING = 0;
    public const TARGET_STATUS_OVER = 1;

    //奖励状态
    public const REWARD_STATUS_CAN_NOT_GET = 0;
    public const REWARD_STATUS_CAN_GET = 1;
    public const REWARD_STATUS_ALREADY_GET = 2;

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

    public function initLevel(int $levelId)
    {
        $this->levelId = $levelId;
        $this->status = self::STATUS_DOING;
        $this->target = "0-0-0";
        $this->rewardStatus = "0-0-0";
        $this->saveDB();
    }

    public function searchDB(int $levelId): bool
    {
        $result = array();
        if (false == $this->searchTitle(
                DBTableDefine::TABLE_PVE_LEVEL,
                $this->playerId,
                $levelId,
                $result
            )
        ) {
            return false;
        }
        $this->formatData($result);
        return true;
    }

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

    private function saveDB(): bool
    {
        $data = array();
        foreach (self::DB_KEY_MAP as $k => $v) {
            $data[$k] = $this->$v;
        }
        return $this->updateTitle(
            DBTableDefine::TABLE_PVE_LEVEL,
            $this->playerId,
            $this->levelId,
            $data,
        );
    }

    private function formatData(array $result)
    {
        foreach ($result as $key => $value) {
            $val = self::DB_KEY_MAP[$key] ?? $key;
            if ($key == self::Status) {
                $this->$val = (int)$value;
            } else {
                $this->$val = $value;
            }
        }
    }
}
