<?php

namespace App\Traits;

use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;

trait Files
{
	/**
	 * Get a list of files
	 */
	public function getFiles(array $option,string $type): Collection
	{
		// Make sure we got a directory or a file to import
		if (is_null($option['file']) AND is_null($option['dir']))
			abort(500,'Missing filename, please use --file= OR --dir=');

		Log::debug(sprintf('%s: Processing: %s',__METHOD__,($option['file'] ? $option['file'] : $option['dir'])));

		$files = collect();
		$dir = '';

		if ($option['dir'] AND is_dir($option['dir'])) {
			// Remove our trailing slash from the directory.
			$dir = preg_replace('/\/$/','',$option['dir']);

			// Exclude . & .. from the path.
			$files = $files->merge(array_filter(array_diff(scandir($dir),array('.','..')),function($item) use ($dir) { return is_file($dir.'/'.$item); }));

		} elseif ($option['file'] AND ! is_dir($option['file']) AND file_exists($option['file'])) {
			$dir = dirname($option['file']);

			$files->push(basename($option['file']));
		}

		// Determine if our dir is relative to where we store data
		$dir = static::path($dir,$type);

		// Add our path
		if ($dir)
			$files->transform(function($value) use ($dir) {
				return sprintf('%s/%s',$dir,$value);
			});

		Log::debug(sprintf('%s: Processing: %s (%s)',__METHOD__,($option['file'] ? $option['file'] : $option['dir']),count($files)));

		return $files;
	}

	/**
	 * Recursively make a parent dir to hold files.
	 *
	 * @param $dir
	 * @return bool
	 */
	public function makeParentDir($dir)
	{
		if (is_dir($dir))
			return TRUE;

		if (! file_exists(dirname($dir)) AND ! $this->makeParentDir(dirname($dir)))
			return FALSE;
		else
			return is_writable(dirname($dir)) AND mkdir($dir);
	}

	/**
	 * Return if the dir is a sub dir of our config.
	 *
	 * @param $path
	 * @param $type
	 * @return string
	 */
	public static function path($path,$type): string
	{
		return (strpos($path,config($type.'.dir').'/') === 0) ? str_replace(config($type.'.dir').'/','',$path) : $path;
	}
}