<?php

namespace app\commands\helpers;

/**
 * Helper trait to provide timing tools to see how long specific command or task takes
 * 
 * @author  Gareth Palmer <gareth@one-space.co.za>
 */

trait Timer {

    /**
     * The precise microsecond the task started.
     * 
     * @var int $startTime
     * 
     * @access  private
     */

    private float $startTime;

    /**
     * The precise microsecond the task started.
     * 
     * @var int $endTime
     * 
     * @access  private
     */

    private float $endTime;


    /**
     * Start the timer.
     * 
     * @access  protected
     */

    protected function startTimer(): void {
        $this->startTime = microtime(true);
    }


    /**
     * End the timer.
     * 
     * @access  protected
     */

    protected function endTimer(): void {
        $this->endTime = microtime(true);
    }


    /**
     * Resets the timer.
     * 
     * @access  protected
     */

    protected function resetTimer(): void {
        $this->startTime = null;
        $this->endTime = null;
    }


    /**
     * Returns the duration of the task as a float.
     * 
     * @param   int|null    $round  The number of decimal places to round to. Set to null to skip. Default: null.
     * 
     * @return  float
     * 
     * @access  protected
     */

    protected function totalDuration(?int $round = null): float {
        if ($round === null) {
            return $this->endTime - $this->startTime;
        }
        return round($this->endTime - $this->startTime, $round);
    }


    /**
     * Echos a textual summary of the duration of the task.
     * 
     * @param   int $round  The number of decimal places to round to. Default: 4.
     * @param   string  $lb The lib
     * 
     * @access  protected
     */

    protected function timerSummary(int $round = 4, string $lb = "\n"): void {
        echo sprintf("The task took %f seconds to complete.%s", $this->totalDuration($round), $lb);
    }
}
