<?php

use App\EntityClassInitialSetup;
use App\EntityClass;
use App\ClassParameter;
use Illuminate\Database\Seeder;

/**
 * Class ClassParametersSeeder
 */
class ClassParametersSeeder extends Seeder
{

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {

        $entityClasses = EntityClass::all();

        DB::transaction(function () use ($entityClasses) {
            foreach ($entityClasses as $entityClass) {

                $definition = EntityClassInitialSetup::getEntityDefinition($entityClass->name);

                if (isset($definition['parameters']) && is_array($definition['parameters']))
                    self::addEntityDefinition($entityClass, $definition['parameters']);
            }
        });
    }

    /**
     * Adds entity class parameters definitions into DB
     *
     * @param EntityClass $entityClass
     * @param array $parameterDefinitions
     */
    protected static function addEntityDefinition(EntityClass $entityClass, $parameterDefinitions)
    {
        Log::debug("Processing following parameter definitions (" . $entityClass->name .
            "): " . print_r($parameterDefinitions, true));

        foreach ($parameterDefinitions as $parameter => $parameterDefinition) {
            ClassParameter::updateOrCreate(
                [
                    'entity_class_id' => $entityClass->id,
                    'parameter_name' => $parameter
                ],
                $parameterDefinition
            );
        }
    }

}

