<?php
/**
 * Created by PhpStorm.
 * User: cbarranco
 * Date: 2/29/16
 * Time: 10:39 AM
 */

namespace Hilco;

use Illuminate\Console\Command;
use Log;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;
use Safilo\HasSharedCustomLoggingTrait;
use Storage;
use Symfony\Bridge\Monolog\Handler\ConsoleHandler;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Trait HasProgressEstimatingTrait
 * @package Safilo
 */
trait HasProgressEstimatingTrait
{    
    private $lastLogTime;
    private $startTime;
    private $currentCount;
    private $totalCount;

    protected function startProgressEstimate($totalCount, $messageFormat = false){
        if ($messageFormat === false){
            $messageFormat = $this->getStartMessageFormat();
        }
        $this->totalCount = $totalCount;
        //$this->>info is defined in Command, howerver I strongly recommend you use some variety of HasCustomLogging so it gets output to a file.
        $this->info(sprintf($messageFormat, $totalCount));

        $this->startTime = time();
        $this->lastLogTime = time();
        $this->currentCount = 0;
    }

    protected function getEstimateMessageFormat(){
        return "Processing file %d of %d. (%s%%%s)";
    }
        
    protected function estimateProgress($messageFormat = false){
        if ($messageFormat === false){
            $messageFormat = $this->getEstimateMessageFormat();
        }
        
        $this->currentCount++;
        if (time() >= $this->lastLogTime+1){
            $percentage = number_format(($this->currentCount / $this->totalCount) * 100, 2);

            $executionTime = time() - $this->startTime;
            $estimatedSecondsRemaining = ($executionTime / $this->currentCount * $this->totalCount) - $executionTime;
            $hours = floor($estimatedSecondsRemaining / 3600);
            $minutes = str_pad(floor(($estimatedSecondsRemaining % 3600) / 60), 2, '0', STR_PAD_LEFT);
            $seconds = str_pad($estimatedSecondsRemaining % 60, 2, '0', STR_PAD_LEFT);
            if ($hours > 0){
                $estimatedRemaining = ", $hours:$minutes:$seconds remaining.";
            }else if ($minutes > 0){
                $estimatedRemaining = ", $minutes:$seconds remaining.";
            }else{
                $estimatedRemaining = ", $seconds seconds remaining.";
            }

            $this->lastLogTime=time();

            //$this->notice is NOT defined in Command, you need to define it in implementations of this.
            $this->notice(sprintf($messageFormat, $this->currentCount, $this->totalCount, $percentage, $estimatedRemaining));
        }
    }
}