<?php

namespace App\Console\Commands;

use App\Enums\DbStatusFieldEnum;
use App\Enums\ProductTypeEnum;
use App\Models\ProductGroup;
use Illuminate\Console\Command;
use Rap2hpoutre\FastExcel\FastExcel;

class EmegrendelesImportProductGroup extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'emegrendeles:importProductGroup {--file= : default database/import/productGroup.xlsx}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Product group importer';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    private function parseNodes($parentNode, $collection)
    {
        $parentNodeName = $parentNode->name;
        $rootNode = false;
        if (! isset($parentNode->parent_id) || is_null($parentNode->parent_id)) {
            // o maga a root Node
            $rootNode = true;
        }

        foreach ($collection as $row) {
            if (isset($row[$parentNodeName])
                && strlen($row[$parentNodeName]) > 0
                && $row[$parentNodeName] !== 'n/a'
            ) {

                $node = [
                    'name' => $row[$parentNodeName],
                    'status' => DbStatusFieldEnum::active,

                ];
                if ($rootNode) {
                    if (ProductTypeEnum::hasValue($node['name'])) {
                        $node['type'] = ProductTypeEnum::getKey($node['name']);
                    } else {
                        $node['type'] = ProductTypeEnum::X();
                    }
                } else {
                    $node['type'] = $parentNode->type;

                }
                $treeNode = $parentNode->children()->create($node);
                $this->parseNodes($treeNode, $collection);
            }
        }

    }

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        // $name = $this->argument('name');
        $collection = (new FastExcel)->sheet(1)->import(
            database_path().'/import/productGroup.xlsx'
        );

        $rootName = array_keys($collection->first())[0];
        $tree = [
            'name' => $rootName,
            'status' => DbStatusFieldEnum::active,
        ];
        \Schema::disableForeignKeyConstraints();
        ProductGroup::truncate();

        $rootNode = ProductGroup::create($tree);
        $this->parseNodes($rootNode, $collection);

        \Schema::enableForeignKeyConstraints();
        $this->info('Import End');

        return 0;
    }
}
