<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class GenerateResource extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:resource {name} {--admin}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This is a command to generate resource with model class name';

    protected function getStub()
    {
        return app_path() . '/Console/Stubs/resource.stub';
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $className = $this->argument('name');
        if ($className === '') {
            $this->error("Model is invalid.");
            return 0;
        }

        $rsName = $className . "Resource";
        $rsFile = app_path() . "/Http/Resources/{$rsName}.php";
        $namespace = "App\Http\Resources";
        $option = $this->option('admin');
        if ($option) {
            $namespace .= "\Admin";
            $rsFile = app_path() . "/Http/Resources/Admin/{$rsName}.php";
        }

        if (file_exists($rsFile)) {
            $this->error("Resource \"{$rsFile}\" already exists.");
            return 0;
        }

        $className = "App\\" . $className;
        $obj = new $className();
        $fillableFields = $obj->getFillable();

        $maxLength = 0;
        foreach ($fillableFields as $item) {
            if (strlen($item) > $maxLength) $maxLength = strlen($item);
        }
        $maxLength += 2;

        $content = file_get_contents($this->getStub());
        $content = str_replace("DummyNamespace", $namespace, $content);
        $content = str_replace("DummyClass", $rsName, $content);

        $itemList = "";
        foreach ($fillableFields as $item) {
            if ($itemList != "") $itemList .= "\r\n\t\t\t";
            $lItem = str_pad("'{$item}'", $maxLength, " ");
            if (in_array($item, ['created_at', 'updated_at'])) {
                $itemList .= "{$lItem} => isset(\$this->{$item}) ? date('Y-m-d H:i:s', strtotime(\$this->{$item})) : null,";
            } else {
                $itemList .= "{$lItem} => \$this->{$item},";
            }
        }

        $content = str_replace("DummyItems", $itemList, $content);
        file_put_contents($rsFile, $content);

        $message = "Created resource file: " . "app/Http/Resources/{$rsName}.php";
        if ($option) $message = "Created resource file: " . "app/Http/Resources/Admin/{$rsName}.php";
        $this->info($message);
    }
}
