<?php

declare(strict_types=1);

namespace Airwire\Commands;

use Airwire\Airwire;
use Airwire\TypehintConverter;
use Illuminate\Console\Command;

class GenerateDefinitions extends Command
{
    public static string $dir;

    protected $signature = 'airwire:generate';

    protected $description = 'Generate TypeScript definitions.';

    public function handle()
    {
        $defaults = [];

        $components = '';

        $typemap = "type TypeMap = {\n";

        $converter = (new TypehintConverter);
        foreach (Airwire::$components as $alias => $class) {
            $defaults[$alias] = (new $class([]))->getState();

            $components .= $converter->convertComponent(new $class([])) . "\n\n";
            $className = $converter->getClassName($class);
            $typemap .= "    '{$alias}': {$className}\n";
        }

        $namedTypes = '';
        foreach ($converter->namedTypes as $alias => $type) {
            $namedTypes .= "type {$alias} = {$type};\n\n";
        }

        $typemap .= '}';

        $defaults = json_encode($defaults);

        file_put_contents(resource_path('js/airwire.ts'), <<<JS
        // This file is generated by Airwire
        export const componentDefaults = {$defaults}

        import Airwire from './../../vendor/archtechx/airwire/resources/js';

        export default window.Airwire = new Airwire(componentDefaults)

        declare global {
            interface Window {
                Airwire: Airwire
            }
        }
        JS);

        file_put_contents(resource_path('js/airwired.d.ts'), <<<JS

        declare global {
            {$namedTypes}
        }

        import './../../vendor/archtechx/airwire/resources/js/airwired'

        declare module 'airwire' {
            export {$typemap}
            {$components}
        }
        JS);
    }
}
