<?php

/**
 * 技巧教学章节数据
 */

namespace Game\Data\PVE;

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

class TeachingSkillChapterData
{
    use PlayerDBHandler;

    public int $playerId;

    public const Id = "Id";
    public const ChapterSchedule = "ChapterSchedule";   //完成关卡进度

    public const DB_KEY_MAP = array(
        self::Id => "id",
        self::ChapterSchedule => "chapterSchedule",
    );

    public int $id;
    public int $chapterSchedule;

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

    //创建章节
    public function createDB(int $id)
    {
        $this->id = $id;
        $this->chapterSchedule = 0;
        $this->saveDB();
    }

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

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

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