<?php

/**
 * 生涯章节信息
 */

namespace Game\Data\PVE;

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

class CareerChapterData
{
    use PlayerDBHandler;

    public int $playerId;

    public const UnlockNextChapterFlag = "UnlockNextChapterFlag";   //解锁下一章标记 0不可解锁 1完成最后一关但星数不满足 2已解锁
    public const NextLevelId = "NextLevelId";                       //下一章第一关Id 完成章节最后一关后创建
    public const StarReward = "StarReward";                         //星级奖励 [taleRewardId,..]
    //其他存储  关卡id->星数

    //标记状态
    public const FLAG_STATUS_UNLOCK = 0;
    public const FLAG_STATUS_CAN_LOCK = 1;
    public const FLAG_STATUS_OVER = 2;

    public const STAR_REWARD_GET = 1;   //星星奖励 已领取

    public int $chapterId;

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

    public function initChapterData()
    {
        $data = array(
            self::UnlockNextChapterFlag => self::FLAG_STATUS_UNLOCK,
            self::StarReward => '[]',
        );
        $this->updateDB($data);
    }

    public function updateDB(array $data): bool
    {
        return $this->updateTitle(
            DBTableDefine::TABLE_CAREER_CHAPTER,
            $this->playerId,
            $this->chapterId,
            $data
        );
    }


    //初始注册使用
    public function registerDB(array $data): bool
    {
        $data[self::UnlockNextChapterFlag] = self::FLAG_STATUS_UNLOCK;
        $data[self::StarReward] = '[]';
        return PlayerDBPipe::getInstance()->createTitle(
            DBTableDefine::TABLE_CAREER_CHAPTER,
            $this->playerId,
            $this->chapterId,
            $data
        );
    }

    public function searchDB(): array
    {
        $result = array();
        if (!$this->searchTitle(
                DBTableDefine::TABLE_CAREER_CHAPTER,
                $this->playerId,
                $this->chapterId,
                $result
            ))
        {
            return [];
        }
        return $result;
    }

    //更新解锁最大章节
    public function updateUnlockChapterId(int $chapterId): bool
    {
        return $this->updateTitle(
            DBTableDefine::TABLE_ACCOUNT,
            $this->playerId,
            0,
            array(
                AccountData::DB_CHAPTER_ID => $chapterId
            ),
        );
    }

    //已解锁最大章节
    public function getUnlockChapterId(): int
    {
        $result = array();
        if (!$this->searchTitle(
            DBTableDefine::TABLE_ACCOUNT,
            $this->playerId,
            0,
            $result
        ))
        {
            return 1;
        }
        return $result[AccountData::DB_CHAPTER_ID] ?? 1;
    }
}
