<?php

/**
 * 福利活动信息
 */

namespace Game\Data\Activity;

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

class WelfareData
{
    use PlayerDBHandler;

    // 7new
    public const NEW_NUMBER = "NewNumber";  // 7日新人领取次数
    public const NEW_RECORD = "NewRecord";  // 领取奖励记录

    // login
    public const LOGIN_RECORD1 = "LoginRecord1"; // 可领取记录
    public const LOGIN_RECORD2 = "LoginRecord2"; // 领取奖励记录

    // week sign in
    public const WEEK_RECORD = "WeekRecord";            // 周任务登录记录

    // week login
    public const WEEK_LOGIN_STATE = "WeekLoginState";            // 周末登录

    public const DB_KEY_MAP = [
        self::NEW_NUMBER => "newNumber",
        self::NEW_RECORD => "newRecord",
        self::LOGIN_RECORD1 => "loginRecord1",
        self::LOGIN_RECORD2 => "loginRecord2",
        self::WEEK_RECORD => "weekRecord",
        self::WEEK_LOGIN_STATE => "weekLoginState",
    ];

    public int $playerID = 0;
    public int $newNumber = 0;
    public int $weekLoginState = 0;
    public array $newRecord = [];
    public array $loginRecord1 = [];
    public array $loginRecord2 = [];
    public array $weekRecord = [];

    public function searchDB(): bool
    {
        $result = array();
        if (!$this->searchTitle(
            DBTableDefine::TABLE_WELFARE,
            $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_WELFARE,
            $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_WELFARE,
        $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);
        }
    }
}
