<?php

namespace App\Console\Commands;

use Log;
use Illuminate\Console\Command;
use Illuminate\Foundation\Bus\DispatchesJobs;
use App\Model\Video;
use App\Model\Tag;
use App\Model\Person;

class VideoImport extends Command
{
	use DispatchesJobs;
	use \App\Traits\Files;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'video:import
		{--dir= : Directory to Parse}
		{--file= : File to Import}
		{--ignoredupe : Ignore duplicate files}
		{--deletedupe : Delete duplicate files}
		{--dumpid3 : Dump ID3 data}
		{--people= : People to reference in video}
		{--tags= : Add tag to video}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Import videos into the database';

    /**
     * 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')],'video');
		if (! count($files))
			exit;

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

		$tags = NULL;
		$t = $p = array();

		// Tags
		if ($this->option('tags'))
		{
			$tags = explode(',',$this->option('tags'));
			$t = Tag::whereIn('tag',$tags)->pluck('id')->toArray();
			if (! $t OR count($t) != count($tags))
			{
				$this->error(sprintf('Tag [%s] dont exist',join('|',$tags)));
				abort(501);
			}
		}

		// People
		if ($this->option('people'))
		{
			$tags = explode(',',$this->option('people'));
			$p = Person::whereIn('tag',$tags)->pluck('id')->toArray();
			if (! $p OR count($p) != count($tags))
			{
				$this->error(sprintf('People [%s] dont exist',join('|',$tags)));
				abort(501);
			}
		}

		$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('video.import.accepted')))
			{
				$this->warn(sprintf('Ignoring [%s]',$file));
				continue;
			}

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

			$c++;

			$o = Video::where('filename',$file)->first();

			if (is_null($o))
			{
				$o = new Video;
				$o->filename = $file;
			}

			if (! is_readable($o->file_path()))
			{
				$this->warn(sprintf('Ignoring [%s], it is not readable',$o->file_path()));
				continue;
			}

			if ($o->exists)
				$this->warn(sprintf('%s [%s] already in DB: %s',$o->objectType(),$file,$o->id));

			$o->save();

			if ($o->wasRecentlyCreated)
				$this->info(sprintf('%s [%s] stored in DB: %s',$o->objectType(),$file,$o->id));

			// Record our people and tags
			if ($p)
				$o->People()->sync($p);
			if ($t)
				$o->Tags()->sync($t);

			$this->dispatch((new \App\Jobs\CatalogScan($o))->onQueue('scan'));

			if ($this->option('dumpid3'))
				dd($o->dump());
		}

		$bar->finish();

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