<?php
declare(strict_types=1);

namespace App;

use DB;
use Illuminate\Database\Eloquent\Model;

/**
 * Class EntityParameter
 * @package App
 */
class EntityParameter extends Model
{
    const STRING_DB_LEN = 4096;

    const STRING = 'str';
    const TINY_INT = 'tiny_int';
    const INT = 'int';
    const DATETIME = 'date_time';
    const BLOB = 'blob_data';

    const ALL_PARAMETERS = [
        self::STRING,
        self::TINY_INT,
        self::INT,
        self::DATETIME,
        self::BLOB
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'entity_id', 'entity_class_parameter_id', self::STRING, self::TINY_INT, self::INT, self::DATETIME, self::BLOB
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        //
    ];

    protected $touches = [
        'entity'
    ];

    /**
     * Uniqueness is check against particular entity_class_parameter_id.
     *
     * @param $entityId
     * @param $classParameterId
     * @param $classParameterType
     * @param $value
     * @return bool
     */
    public static function isUnique($entityId, $classParameterId, $classParameterType, $value)
    {
        $where = [
            ['p.entity_class_parameter_id', '=', $classParameterId],
            ['p.' . $classParameterType, '=', $value],
        ];

        if ($entityId !== null) {
            $where[] = ['d.id', '!=', $entityId];
        }

        $foundSomething = DB::table('parameters as p')
            ->join('entities as d', 'p.entity_id', '=', 'd.id')
            ->select($classParameterType)
            ->where($where)
            ->first();

        return $foundSomething === null;
    }
}