<?php

namespace AuthStack\Driver\Connection\Model;

use Illuminate\Database\Eloquent\Model;

class Connection extends Model
{
    protected $table = 'drivers_connections';
    protected $fillable = ['driver_id', 'title', 'configuration', 'created_at', 'updated_at'];
    public $timestamps = true;

    protected $casts = [
        'configuration' => 'array'
    ];


    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function driver()
    {
        return $this->belongsTo(Driver::class);
    }


    /**
     * @return mixed
     */
    public function getDriverClass()
    {
        return $this->driver->getAttribute('class_path');
    }


    /**
     * @return array
     */
    public function getConnectionConfig()
    {
        $cfg = $this->getAttribute('configuration');

        if(empty($cfg)) $cfg = [];

        return $cfg;
    }


    /**
     * @return array
     */
    public function getAttributeList()
    {
        $result = [];

        if(isset($this->configuration) && is_array($this->configuration) && isset($this->configuration['attribute_list']))
        {
            $result = $this->configuration['attribute_list'];
        }

        return $result;
    }

    /**
     * @param $value
     */
    public function setConfigurationAttribute($value)
    {
        $this->attributes['configuration'] = json_encode($value, JSON_UNESCAPED_SLASHES);
    }
}