<?php

namespace Api\PhpUtils\Mon;


class TimeCostUtil
{
    private $time_costs;
    public static $one;

    private function __construct()
    {
        $this->time_costs = array();
    }

    public static function getSingleton()
    {
        if (self::$one === null)
        {
            self::$one = new TimeCostUtil();
            self::$one->record_time('req_all_cost');
        }
        return self::$one;
    }

    public function record_time($name)
    {
        $this->time_costs[$name][] = microtime(true);
    }

    /**
     * 获取消耗的时间
     * @param $name
     * @return bool|mixed
     */
    public function get_time_cost($name)
    {
        if (isset($this->time_costs[$name]) && count($this->time_costs[$name]) === 2)
        {
            return $this->time_costs[$name][1] - $this->time_costs[$name][0];
        }

        return false;
    }

    /**
     * 获取所有消耗的时间
     * @param $modules
     * @return array
     */
    public function get_all_time_cost($modules='')
    {
        if(empty($modules)) {
            $modules = $_SERVER['SERVER_NAME'] ?? '';
        }

        //因grafana打点路径以"."分割，将服务器名中的"."转化为"_"
        $modules = str_replace(".", "_", $modules);

        if (self::$one !== null) {
            self::$one->record_time('req_all_cost');
        }
        $result = array();
        foreach ($this->time_costs as $name => $times)
        {
            if (count($times) === 2)
            {
                $result[$name] = $times[1] - $times[0];
                MonUtil::send_time_cost_msg($modules,$name, $result[$name]);
            } else {
                $result[$name] = false;
            }
        }

        return $result;
    }
}