<?php

/**
 * 地图结算统计数据
 */

namespace Game\Data;

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

class MapStatisticsData
{
    use PlayerDBHandler;

    public int $playerId;

    private string $titleId;

    public const JAM_NUM = "JamNum";    //干扰次数
    public const HELP_NUM = "HelpNum";  //辅助次数
    public const MAX_SPEED = "MaxSpeed";    //最高速度
    public const AVG_SPEED = "AvgSpeed";    //平均速度
    public const N2_COVER = "N2Cover";  //氮气覆盖
    public const ADVANCE = "Advance";   //进阶技巧
    public const LEAD_RATIO = "LeadRatio";  //领跑占比
    public const DRIFT_RANGE = "DriftRange";    //漂移距离
    public const CONTINUITY_WIN_NUM = "ContinuityWinNum";   //连胜次数
    public const COST_TIME = "CostTime";    //比赛用时

    public const DB_KEY_MAP = array(
        self::JAM_NUM => "jamNum",
        self::HELP_NUM => "helpNum",
        self::MAX_SPEED => "maxSpeed",
        self::AVG_SPEED => "avgSpeed",
        self::N2_COVER => "n2Cover",
        self::ADVANCE => "advance",
        self::LEAD_RATIO => "leadRatio",
        self::DRIFT_RANGE => "driftRange",
        self::CONTINUITY_WIN_NUM => "continuityWinNum",
        self::COST_TIME => "costTime",
    );

    public int $jamNum = 0;
    public int $helpNum = 0;
    public int $maxSpeed = 0;
    public int $avgSpeed = 0;
    public float $n2Cover = 0;
    public int $advance = 0;
    public float $leadRatio = 0;
    public int $driftRange = 0;
    public int $continuityWinNum = 0;
    public int $costTime = 0;

    //破记录标记
    public const BREAKING_FLAG_WEEK = 3;
    public const BREAKING_FLAG_MOTH = 2;
    public const BREAKING_FLAG_HISTORY = 1;

    public function __construct(int $playerId, int $mapId, int $title)
    {
        $this->playerId = $playerId;
        $this->titleId = $mapId . "#" . $title;
    }

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

    public function searchDB()
    {
        $this->searchTitle(
            DBTableDefine::TABLE_MAP_STATISTICS,
            $this->playerId,
            $this->titleId,
            $result
        );
        $this->formatData($result);
    }

    //删除表--跨周,月 删除数据
    public function clearTable(): bool
    {
        return $this->deleteTable(
            DBTableDefine::TABLE_MAP_STATISTICS,
            $this->playerId,
            $this->titleId
        );
    }

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