<?php

/**
 * 驾照考试--章节
 */

namespace Game\Data\PVE;

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

class ExamData
{
    use PlayerDBHandler;

    public int $playerId;

    public const Id = "Id";
    public const ExamSchedule = "ExamSchedule";   //大奖进度
    public const DrivingLicenseDate = "DrivingLicenseDate"; //驾照获得日期

    public const DB_KEY_MAP = array(
        self::Id => "id",
        self::ExamSchedule => "examSchedule",
        self::DrivingLicenseDate => "drivingLicenseDate"
    );

    public int $id;
    public int $examSchedule;
    public int $drivingLicenseDate;

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

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

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

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

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

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

