<?php

namespace AuthStack\Driver\Connection\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use AuthStack\Driver\Errors\InvalidDriverAttributesError;

class Driver extends Model
{
    protected $table = 'drivers';
    protected $fillable = ['title', 'description', 'class_path', 'num_connections', 'created_at', 'updated_at'];
    public $timestamps = true;


    /**
     * @param array $attributes
     *
     * @return Driver
     */
    public static function install(array $attributes)
    {
        static::checkAttributes($attributes);

        $attributes['unique_id'] = sha1($attributes['class_path'], true);

        try {
            $model = static::where('unique_id', $attributes['unique_id'])->firstOrFail();
        } catch (ModelNotFoundException $e) {
            // No such record
            $model = static::create($attributes);
        } catch (\PDOException $e) {
            $model = static::where('unique_id', $attributes['unique_id'])->firstOrFail();
        }

        return $model;
    }


    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function driverConnection()
    {
        return $this->hasMany(Connection::class);
    }


    /**
     * @param array $data
     *
     * @return Connection
     */
    public function addDriverConnection(array $data)
    {
        return $this->driverConnection()->create($data);
    }


    /**
     * @param array $attributes
     *
     * @throws InvalidDriverAttributesError
     */
    protected static function checkAttributes(array $attributes)
    {
        $required = ['title', 'description', 'class_path'];

        foreach ($required as $key) {
            if (!isset($attributes[$key])) {
                throw new InvalidDriverAttributesError(sprintf('Required key %s not specified in the attributes array', $key));
            }
        }
    }
}