<?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;

/**
 * @phpstan-import-type HashObject from \App\Types\SubmissionTypes
 */
class HashesChecker extends Component
{

    /**
     * Current hash.
     * @var null|HashObject $hash
     */
    public ?array $hash = null;

    /**
     * Add a hash.
     *
     * @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->hash = [
                'filename' => $filename,
                'hash_crc32' => $crc32,
                'hash_sha1' => $sha1,
                'verified' => $verified
            ];
        else if( ( $hash = HashesHelpers::findHashes( $sha1 ) ) !== null )
            $this->hash = [
                'filename' => $hash->filename,
                'hash_crc32' => $hash->crc32,
                'hash_sha1' => $hash->sha1,
                'verified' => HashesHelpers::getReferenceName( $hash->dat_reference_id )
            ];
        else
            $this->hash = [
                'filename' => $filename,
                'hash_crc32' => $crc32,
                'hash_sha1' => $sha1,
                'verified' => "No"
            ];
    }

    /**
     * Remove the hash.
     *
     * @return void
     */
    public function removeHash(): void
    {
        $this->hash = null;
        $this->dispatch('refresh');
    }


    public function render(): View
    {
        $entries = collect();
        if( $this->hash !== null ){
            $entries = EntryHash::where('hash_sha1', $this->hash['hash_sha1'] )->get()->pluck('entry')->filter();
        }
        return view('livewire.hashes-checker', compact('entries'));
    }
}
