<?php

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

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

use App\Models\File;

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

	/**
	 * Count the lines in a file
	 * Assumes $file is compressed with ZIP
	 */
	private function getFileLines(mixed $f): int
	{
		$c = 0;

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

		return $c;
	}

	private function openFile(string $file): \ZipArchive
	{
		$z = new \ZipArchive;

		if ($z->open($file,\ZipArchive::RDONLY) === TRUE) {
			return $z;

		} else {
			throw new \Exception(sprintf('%s:! Failed opening ZipArchive [%s] (%s)',self::LOGKEY,$file,$z->getStatusString()));
		}
	}

	/**
	 * 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 $key,mixed $file): string
	{
		if ($file instanceof File) {
			$path = sprintf('import/%s.%d',$key,$file->id);

			Storage::disk(config('fido.local_disk'))->put($path,Storage::get($file->rel_name));

			return Storage::disk(config('fido.local_disk'))->path($path);

		} else {
			return Storage::disk(config('fido.local_disk'))->path($file);
		}
	}
}