<?php

namespace App\Console\Commands;

use Illuminate\Support\Facades\Log;
use Illuminate\Console\Command;

use App\Traits\Files;
use App\Models\Photo;

class PhotoMove extends Command
{
	use Files;

	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'photo:move
		{--file= : Photo File}
		{--id= : Photo ID}';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Moves Photos to their new location';

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

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function handle()
	{
		if ($this->option('file')) {
			$po = Photo::notRemove()->notDuplicate()->where('filename',Photo::path($this->option('file')));

		} elseif ($this->option('id')) {
			$po = Photo::notRemove()->notDuplicate()->where('id',$this->option('id'));

		} else {
			$po = Photo::notRemove()->notDuplicate();
		}

		if (! $po)
			exit;

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

		$po->chunk(1,function($photo) use ($bar) {
			while ($o = $photo->shift()) {
				if (($x = $o->moveable()) === TRUE) {
					Log::info(sprintf('%s: Moving (%s)[%s]',__METHOD__,$o->id,$o->filename));

					if ($this->makeParentDir(dirname($o->file_path(FALSE,TRUE))) AND rename($o->file_path(),$o->file_path(FALSE,TRUE))) {
						// Convert the path to a relative one.
						$o->filename = $o->file_path(TRUE,TRUE);

						// @todo If the DB update failed, move it back.
						if (! $o->save()) # AND ! rename($path,$o->file_path()))
						{
							$this->error(sprintf('Save after rename failed for (%s)',$o->id));
							continue;
						}

					} else {
						$this->error(sprintf('Rename failed for (%s)',$o->id));
						continue;
					}

					chmod($o->file_path(),0444);

				} else {
					if ($x > 0)
						$this->warn(sprintf('Unable to move (%s) [%s] to [%s], movable returned (%s)',$o->id,$o->file_path(),$o->file_path(FALSE,TRUE),$x));
				}
			}

			$bar->advance();
		});
	}
}