<?php

/**
 * Import from files
 */
namespace App\Traits;

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

trait Import
{
	protected Collection $_columns; // Columns in the Import File

	/**
	 * Count the lines in a file
	 */
	private function getFileLines(string $file): int
	{
		$f = fopen($file,'r');
		$c = 0;

		while (! feof($f)) {
			fgets($f);
			$c++;
		}

		fclose($f);

		return $c;
	}

	/**
	 * Return the columns from the file that we'll work with
	 *
	 * @param string $line
	 * @return Collection
	 */
	private function getColumns(string $line): Collection
	{
		$this->_columns = collect(explode(',',strtoupper($line)))->filter();
		return $this->_columns->intersect($this->columns);
	}

	/**
	 * Get the index for the column in the file
	 *
	 * @param string $key
	 * @return int|null
	 */
	private function getColumnKey(string $key): ?int
	{
		return ($x=$this->_columns->search(strtoupper($this->columns->get($key)))) !== FALSE ? $x : NULL;
	}

	private function getFileFromHost(string $host,string $key,string $file): string
	{
		$path = 'import/'.$key;

		// If we are doing it locally, we dont need to retrieve it via curl
		if (! $host) {
			return preg_match('/^data/',$file) ? $file : sprintf('storage/app/public/%s/%s',$path,basename($file));
		}

		// Get the file from the host
		$srcfile = sprintf('http://%s%s',$host,$file);
		$dstfile = '/tmp/'.basename($host);
		Log::debug(sprintf('%s:Retrieving [%s] from [%s]',static::LOGKEY,$host,$file));

		$src = fopen($srcfile,'r');
		$dst = fopen($dstfile,'w');
		stream_copy_to_stream($src,$dst);
		fclose($src);
		fclose($dst);

		// Store the file for later processing
		Storage::putFileAs($path,$dstfile,basename($file));

		return Storage::path($path.'/'.basename($file));
	}
}