<?php

namespace App\Console\Commands;

use Log;
use Illuminate\Console\Command;
use App\Model\Photo;

class PhotoUpdate extends Command
{
	use \App\Traits\Files;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'photo:update
		{--dir= : Directory to Parse}
		{--file= : File to import}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update Signatures';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
		$files = $this->getFiles(['dir'=>$this->option('dir'),'file'=>$this->option('file')]);
		if (! count($files))
			exit;

		// Show a progress bar
		$bar = $this->output->createProgressBar(count($files));
		$bar->setFormat("%current%/%max% [%bar%] %percent:3s%% (%memory%) (%remaining%) ");

		$c = 0;
		foreach ($files as $file)
		{
			$bar->advance();

			if (preg_match('/@__thumb/',$file) OR preg_match('/\/._/',$file))
			{
				$this->warn(sprintf('Ignoring file [%s]',$file));
				continue;
			}

			if (! in_array(strtolower(pathinfo($file,PATHINFO_EXTENSION)),config('photo.import.accepted')))
			{
				$this->warn(sprintf('Ignoring [%s]',$file));
				continue;
			}

			if ($this->option('verbose'))
				$this->info(sprintf('Processing file [%s]',$file));

			$c++;

			$po = Photo::where('filename',$file)->first();

			if (is_null($po))
			{
				$this->error(sprintf('File is not in the database [%s]?',$file));
				Log::error(sprintf('%s: File is not in the database [%s]?',__METHOD__,$file));
				continue;
			}

			$po->signature = $po->property('signature');

			try {
				$po->thumbnail = exif_thumbnail($po->file_path());
			} catch (\Exception $e) {
				// @todo Couldnt get the thumbnail, so we should create one.
			}

			if ($po->isDirty())
			{
				if (count($po->getDirty()) > 1 OR ! array_key_exists('signature',$po->getDirty()))
					$this->error(sprintf('More than the signature changed for [%s] (%s)?',$po->id,join('|',array_keys($po->getDirty()))));

				$this->info(sprintf('Signature update for [%s]',$po->id));
				$po->save();
			}
		}

		$bar->finish();

		return $this->info(sprintf('Images processed: %s',$c));
	}
}