<?php

namespace App\Console\Commands;

use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

#[Signature('hashes:import-dat {file}')]
#[Description('Import a hashes DAT file like No-Intro/Redump')]
class ImportDatFile extends Command
{
    /**
     * Execute the console command.
     */
    public function handle()
    {
        $file = $this->argument('file');

        if(!file_exists($file)) {
            $this->error('File not found');
            return;
        }

        $reader = new \XMLReader();
        $reader->open($file);

        $this->info("Importing...");

        $count = 0;
        $insertBuffer = [];
        $datReferenceId = null;

        while ($reader->read()) {
            if($reader->nodeType == \XMLReader::ELEMENT) {
                if( $reader->name == 'header' ){
                    $node = new \SimpleXMLElement($reader->readOuterXml());
                    $name = (string) ($node->name . ' v.' . $node->version . ' (' . $node->homepage . ')');
                    DB::connection('hashes')->table('dat_reference')->insert([['name' => $name ]]);
                    $datReferenceId = DB::connection('hashes')->table('dat_reference')->where('name', $name)->value('id');
                }

                if( $reader->name == 'game' ){
                    if( !$datReferenceId ){
                        $this->error("No dat reference found");
                        return;
                    }
                    $node = new \SimpleXMLElement($reader->readOuterXml());
                    foreach ($node->rom as $rom) {
                        $insertBuffer[] = [
                            'filename' => $rom['name'],
                            'crc32' => $rom['crc'],
                            'sha1' => $rom['sha1'],
                            'dat_reference_id' => $datReferenceId,
                        ];
                        $count++;

                        if( count($insertBuffer) >= 1000 ){
                            DB::connection('hashes')->table('hashes')->insert($insertBuffer);
                            $insertBuffer = [];
                        }
                    }
                }
            }
        }

        if( count($insertBuffer) >= 0 ){
            DB::connection('hashes')->table('hashes')->insert($insertBuffer);
        }

        $reader->close();
        $this->info("{$count} ROMs hashes imported.");
    }
}
