<?php

namespace App\Models\PHPXPress;

use App\Collections\Autoflow\PHPXPress\ColumnsCollection;
use App\Models\Model;
use function d;

class RepositoryColumns extends Model {

    protected $table = 'repository_columns';
    protected $connection = 'phpxpress';
    public $timestamps = false;
    protected $primaryKey = 'ID';
    protected $fillable = [];
    public static $id = '1febb00c2845d110a1a14bd5e2e336ac02b5e437';
    public $incrementing = false;

    public $is_expandable = true;

    public function newCollection(array $models = []) {
        return new ColumnsCollection($models);
    }

    public function getFileExtension() {
        throw new \Exception('deprecated');
        switch($this->identifier) {
            case 'file:blade':
                return '.blade.php';
                break;
            case 'file:php':
                return '.php';
                break;
            default:
                throw new \Exception('unknown file type ' . $this->identifier);
        }
    }

    // Diese Spalte als automatisch aufgelöste sollte gut überlegt sein :-)
    // Zugriff daher momentan nur manuell mittels $this->>_repository()
    public function _repository() {
        return $this->belongsTo('\App\Models\PHPXPress\Repository', '_repository', 'ID');
    }

    public function _format() {
        return $this->hasOne('\App\Models\PHPXPress\ColumnFormats', 'ID', '_format');
    }


    // DAS DING HIER MÜSSEN WIR _constraints NENNEN WEIL _constraint NICHT FUNKTIONIERT: WTF

    public function _constraints() {
        if("backlink" == $this->identifier)
            return $this->hasOne('\App\Models\PHPXPress\Constraints', '_backlink', 'ID');
        else
            return $this->hasOne('\App\Models\PHPXPress\Constraints', '_column', 'ID');
    }

    /************************ ACHTUNG *********************/
    /** Anscheinend sind die beiden Funktionen vertauscht */
    /** _constraint() liefert den Backlink, _backlink() liefert den constraint */

    public function getAssociatedColumn() {

        switch($this->identifier) {
            case "constraint":
                return $this->_backlink()->first();
                break;
            case "backlink":
                return $this->_column()->first();
                break;
            default:
                throw new \Exception('invalid');
        }
    }

    public function getAssociatedRepository() {
        throw new \Exception('correct joins');
        switch($this->signifier):
            case "pivot":
                return (new \App\Models\PHPXPress\Joins());
                break;
            default:
                return $this->getAssociatedColumn()->load('_repository')->_repository->make();
                break;
        endswitch;
    }

    public function _column() {
        return $this->belongsTo(self::class, '_column', 'ID');
    }

    /**public function _constraint() {

        throw new \Exception('deprecated');

        return $this->belongsTo(self::class, '_column', 'ID');

    } **/

    public function _backlink() {

        return $this->belongsTo(self::class, '_backlink', 'ID');

        /**if($cached = \Cache::store('array')->get('constraints.'.$this->getKey())) return $cached;
        $constraint = self::findOrFail($this->getAttribute('_column'));
        $constraint->relations['_repository'] = \Runtime::make()->findOrFail($constraint->getAttribute('_repository'));
        return $constraint; **/
    }

    public function _left_key() {
        return $this->belongsTo(self::class, '_left_key', 'ID');
    }

    public function _right_key() {

        return $this->belongsTo(self::class, '_right_key', 'ID');
    }

    /******************************************************/

    public function castValue($value) {

        $this->_format->_type->_data_type->getKey();

        switch($this->_format->_type->_data_type->getKey()) {
            case 1:
                return (int) $value;
                break;
            case 2:
                return strval($value);
                break;
            case 3:
                return $value;
                break;
            case 4:
                return $value;
                break;
            case 9:
                if('boolean' == $this->laravel_data_type) $value ? 1 : 0;
                else return empty($value) ? NULL : $value;
                break;
            case 10:
                return $value;
                break;
            case 11:
                return $value;
                break;
            case 12:
                return (float) $value;
                break;
            case 13:
                return (bool) $value;
                break;
            default:
                d($this);
                throw new \Exception('unsupported data type ' . $this->laravel_data_type);
                break;
        }
    }

    public function getDefault() {
        return $this->castValue($this->default);
    }

    public function hasNested() {
        if($this->_nested_columns AND $this->_nested_columns->count()) return true;
        else return false;
    }
    
    public function createColumn() {
    
        $schema = \Schema::connection($this->_repository->getAttributeValue('_database'));

        $model = $this;
        
        switch($this->form->identifier) {

        
            case "column":

                $schema->table($this->_repository->signifier, function ($table) use ($model) {

                    switch ($model->_format->identifier) {

                        case "webimage":
                        case "varchar255":
                            $x = $table->string($model->signifier, 255);
                            $x->nullable();
                            break;

                        case "html":
                        case "text":
                            $x = $table->text($model->signifier);
                            $x->nullable();
                            break;

                        case 'int_unsigned':
                            $x = $table->integer($model->signifier);
                            $x->nullable();
                            $x->unsigned();
                            $x->default(0);
                            break;

                        case 'float_unsigned':
                            $x = $table->double($model->signifier);
                            $x->nullable();
                            $x->unsigned();
                            $x->default(0);
                            break;

                        /**case "float":
                            $x = $table->double($model->signifier);
                            $x->nullable();
                            if($model->default) $x->default($model->default);
                            if($model->unsigned) $x->unsigned();
                            break; **/

                        case "checkbox":
                        case "boolean":
                        case "toggle":
                            $x = $table->boolean($model->signifier);
                            $x->nullable();
                            $x->default(0);
                            break;

                        case "date":
                            $x = $table->date($model->signifier);
                            $x->nullable();
                            break;

                        case "backlink":
                            break;

                        default:
                            throw new \Exception('unsupported data type ' .$model->_format->identifier);

                    }
                });
                break;

            case "has_one":
            case "single_choice":

                $schema->table($model->_repository->signifier, function ($table) use ($model) {
                    $x = $table->string($model->signifier);
                    $x->nullable();
                });

                break;

            case "attachment":

                $constraint = \Runtime::make($model->getAttribute('_constraint'));

                $schema->table($constraint->getConfig()->signifier, function ($table) use ($model) {
                    $x = $table->string($model->signifier. '_at_' .$model->_repository->signifier );
                    $x->nullable();
                });

                break;

        }
    
    
    }

}
