<?php

/**
 * 限时任务
 */

namespace Game\Data\Activity;

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

class LimitTimeData
{
    use PlayerDBHandler;

    // 开启活动 ID 记录
    public const EXCHANGE_RECORD = "ExchangeRecord";       // 开启的限时任务


    public const DB_KEY_MAP = [
        self::EXCHANGE_RECORD => "exchangeRecord",
    ];

    public int $playerID = 0;
    public array $exchangeRecord = [];

    public function searchDB(): bool
    {
        $result = array();
        if (!$this->searchTitle(
            DBTableDefine::TABLE_TASK_LIMIT_TIME_DATA,
            $this->playerID,
            0,
            $result)
        ) {
            return false;
        }
        foreach ($result as $k => $v) {
            $this->setDBData($k, $v);
        }
        return true;
    }

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

    public function registerDB(): bool
    {
        $data = array();
        foreach (self::DB_KEY_MAP as $k => $v) {
            if (is_numeric($this->$v)) {
                $data[$k] = $this->$v;
            } else {
                $data[$k] = json_encode($this->$v);
            }
        }
        return PlayerDBPipe::getInstance()->createTitle(
            DBTableDefine::TABLE_TASK_LIMIT_TIME_DATA,
            $this->playerID,
            0,
            $data
        );
    }

    private function setDBData($key, $value)
    {
        if (!array_key_exists($key, self::DB_KEY_MAP)) {
            return;
        }
        $property = self::DB_KEY_MAP[$key];
        if (is_numeric($this->$property)) {
            $this->$property = (int)$value;
        } else {
            $this->$property = json_decode($value, true);
        }
    }
}
