<?php

class Core_Timer_Timer
{

    /**
     * @var string
     */
    protected $name;

    /**
     * @var float
     */
    protected $timeStart;

    /**
     * @var array
     */
    protected $history;

    /**
     * @var Core_Timer_Timer[] $instances
     */
    protected static $instances = array();

    /**
     * @var string[]
     */
    protected static $uniqueFilesNames = array();

    /**
     * @param string $name
     */
    protected function __construct($name)
    {
        $this->name = $name;
        $this->start();
    }

    public function __destruct()
    {
        $this->save();
    }

    /**
     * @param string $name
     *
     * @return Core_Timer_Timer
     */
    public static function getInstance($name)
    {
        if (!isset(self::$instances[$name])) {
            self::$instances[$name] = new Core_Timer_Timer($name);
        }

        return self::$instances[$name];
    }

    /**
     * for debug purposes only
     *
     * @return Core_Timer_Timer[]
     */
    public static function getInstances()
    {
        return self::$instances;
    }

    /**
     * @param string $name
     *
     * @return string
     */
    public static function getUniqueFileName($name)
    {
        if (!isset(self::$uniqueFilesNames[$name])) {
            /**
             * @var Core_Config $config
             */
            $config = Core_Application::get('config')->toArray();
            $folder = isset($config['app']['log']['path']) ? $config['app']['log']['path'] : sys_get_temp_dir() . '/timer/';
            if (!file_exists($folder)) {
                mkdir($folder, 0777, true);
            }

            $filename = sprintf(
                'timer_%s_%s_',
                time(),
                $name
            );


            self::$uniqueFilesNames[$name] = tempnam($folder, $filename);
        }

        return self::$uniqueFilesNames[$name];
    }

    public function start()
    {
        $this->timeStart = time() + microtime();
    }

    /**
     * @param string $name
     */
    public function stop($name = '')
    {
        $this->history[] = sprintf(
            '%d) %s %s ',
            count($this->history) + 1,
            $name,
            (time() + microtime() - $this->timeStart)
        );
    }

    /**
     * @return int
     */
    public function save()
    {
        if (!Core_Application::get('request')->isDebug()) {
            return 0;
        }

        return file_put_contents(
            self::getUniqueFileName($this->name),
            implode("\n", $this->history) . "\n",
            FILE_APPEND
        );
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @return array
     */
    public function getHistory()
    {
        return $this->history;
    }

} 