<?php

namespace Hilco\Models;

use DB;
use Illuminate\Database\Eloquent\Builder;
use Ramsey\Uuid\Uuid;

trait UuidForKey
{
//	/**
//	 * This function overwrites the default boot static method of Eloquent models. It will hook
//	 * the creation event with a simple closure to insert the UUID
//	 */
//	public static function bootUuidForKey()
//	{
//		static::creating(function ($model){
//			$model->incrementing                       = false;
//			$uuidVersion                               = (! empty($model->uuidVersion) ? $model->uuidVersion : 4);   // defaults to 4
//			$uuid                                      = Uuid::generate($uuidVersion);
//			$model->attributes[ $model->getKeyName() ] = $uuid->bytes;
//		}, 0);
//
////		static::addGlobalScope('uuidScope', function(Builder $builder) {
////			return $builder->select(['*', DB::raw('UuidFromBin(id) as id')]);
////		});
//	}

	/**
	 * Get the casts array.
	 * @return array
	 */
	public function getCasts()
	{
		return $this->casts;
	}


	/**
	 * This function is used internally by Eloquent models to test if the model has auto increment value
	 * @return bool
	 */
	public function getIncrementing()
	{
		return false;
	}

	/**
	 * Gets the binary field as hex string ($model->id_string)
	 * @return string The string representation of the binary field.
	 */
	public function getIdStringAttribute()
	{
		return bin2hex($this->attributes['id']);
	}

	/**
	 * Modified find static function to accept both string and binary versions of uuid
	 *
	 * @param  mixed $id      The id (binary or hex string)
	 * @param  array $columns The columns to be returned (defaults to *)
	 *
	 * @return mixed           The model or null
	 */
	public static function find($id, $columns = ['*'])
	{
		if(ctype_print($id)){
			return static::where('id', '=', hex2bin($id))->first($columns);
		}
		else{
			return parent::where('id', '=', $id)->first($columns);
		}
	}
}