<?php


namespace App\Helpers\DatabaseSchema;


use Closure;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\ColumnDefinition;
use Illuminate\Database\Schema\ForeignIdColumnDefinition;
use Illuminate\Database\Schema\ForeignKeyDefinition;
use Illuminate\Support\Fluent;
use Illuminate\Support\Str;

class CustomBluePrint extends Blueprint{


    public function __construct($table, Closure $callback = null, $prefix = ''){
        parent::__construct($table, $callback, $prefix);
    }

    /**
     * Create a foreign ID column for the given model.
     *
     * @param  Model|string  $model
     * @param  string|null  $column
     * @return CustomForeignIdColumnDefinition|ColumnDefinition
     */
    public function foreignIdFor($model, $column = null){
        if (is_string($model)) {
            $model = new $model;
        }

        return $model->getKeyType() === 'int' && $model->getIncrementing()
            ? $this->foreignId($column ?: $model->getForeignKey())
            : $this->foreignString($column ?: $model->getForeignKey());
    }

    /**
     *
     *
     * @param  string  $column
     * @return ForeignIdColumnDefinition|ColumnDefinition
     */
    public function foreignString($column){
        return $this->addColumnDefinition(new CustomForeignIdColumnDefinition($this, [
            'type' => 'string',
            'name' => $column,
            "length" => 100,
        ]));
    }

    /**
     * Specify a foreign key for the table.
     *
     * @param  string|array  $columns
     * @param  string|null  $name
     * @return \Illuminate\Database\Schema\ForeignKeyDefinition
     */
    public function foreignss($columns, $name = null){
        $command = new ForeignKeyDefinition(
            $this->indexCommand('foreign', $columns,$name ?? uniqid("INDX_"))->getAttributes()
        );

        $this->commands[count($this->commands) - 1] = $command;

        return $command;
    }

    /**
     * Add a new index command to the blueprint.
     *
     * @param  string  $type
     * @param  string|array  $columns
     * @param  string  $index
     * @param  string|null  $algorithm
     * @return Fluent
     */
    protected function indexCommand($type, $columns, $index, $algorithm = null){
        $columns = (array) $columns;

        // If no name was specified for this index, we will create one using a basic
        // convention of the table name, followed by the columns, followed by an
        // index type, such as primary or index, which makes the index unique.
        $index = $index ?: $this->createIndexName($type, $columns);

        $index = strlen($index) > 64 ? uniqid("INDX_") : $index;

        return $this->addCommand(
            $type, compact('index', 'columns', 'algorithm')
        );
    }
}
