<?php

namespace App\Livewire;

use App\Helpers\HashesHelpers;
use App\Models\EntryHash;
use App\Models\Game;
use App\Models\Genre;
use App\Models\Platform;
use Illuminate\View\View;
use Livewire\Component;

/**
 * Hashes uploader in submission form.
 * Upload hash and create fields.
 *
 * @phpstan-import-type HashObject from \App\Types\SubmissionTypes
 */
class HashesUpload extends Component
{

    /**
     * List of hashes.
     * @var list<HashObject> $hashes
     */
    public array $hashes = [];

    /**
     * Prepare old hashes.
     *
     * @param list<HashObject> $oldHashes
     * @return void
     */
    public function mount( array $oldHashes = [] ): void
    {
        foreach ($oldHashes as $hash) {
            if( isset( $hash['filename'], $hash['hash_crc32'], $hash['hash_sha1'], $hash['verified'] ) )
                $this->addHash( $hash['filename'], $hash['hash_crc32'], $hash['hash_sha1'], $hash['verified'] );
        }

    }

    /**
     * Add an hash to the list.
     *
     * @param string $filename
     * @param string $crc32
     * @param string $sha1
     * @param string|null $verified
     *
     * @return void
     */
    public function addHash(string $filename, string $crc32, string $sha1, ?string $verified =  null): void
    {

        if( $verified !== null && $verified !== "No" )
            $this->hashes[] = [
                'filename' => $filename,
                'hash_crc32' => $crc32,
                'hash_sha1' => $sha1,
                'verified' => $verified
            ];
        else if( ( $hash = HashesHelpers::findHashes( $sha1 ) ) !== null )
            $this->hashes[] = [
                'filename' => $hash->filename,
                'hash_crc32' => $hash->crc32,
                'hash_sha1' => $hash->sha1,
                'verified' => HashesHelpers::getReferenceName( $hash->dat_reference_id )
            ];
        else
            $this->hashes[] = [
                'filename' => $filename,
                'hash_crc32' => $crc32,
                'hash_sha1' => $sha1,
                'verified' => "No"
            ];
    }

    /**
     * Remove a specific hash.
     *
     * @param int $index
     * @return void
     */
    public function removeHash(int $index): void
    {
        array_splice($this->hashes, $index, 1);
    }


    public function render(): View
    {
        return view('livewire.hashes-upload');
    }
}
