<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

/**
 * Class CreateEntityClassParametersTable
 */
class CreateClassParametersTable extends Migration
{
    protected $tableName = 'class_parameters';
    protected $tableParamTypesName = 'parameter_datatypes';

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create($this->tableParamTypesName, function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
        });

        DB::transaction(function () {

            $table = DB::table($this->tableParamTypesName);

            foreach (\App\EntityParameter::ALL_PARAMETERS as $parameter) {
                $table->insert([
                    'name' => $parameter
                ]);
            }
        });

        Schema::create($this->tableName, function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('entity_class_id');
            $table->unsignedInteger('parameter_type_id');
            $table->string('parameter_name');
            $table->integer('max_param_len_or_val')->nullable();
            $table->boolean('required')->default(false);
            $table->boolean('unique')->default(false);
            $table->timestamps();

            $table->foreign('entity_class_id')
                ->references('id')->on('entity_classes')
                ->onUpdate('cascade')->onDelete('cascade');

            $table->foreign('parameter_type_id')
                ->references('id')->on($this->tableParamTypesName)
                ->onUpdate('cascade')->onDelete('restrict');
        });


    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists($this->tableName);
        Schema::dropIfExists($this->tableParamTypesName);
    }
}
