<?php

namespace Vinteract\Resources;

use \Vinteract\Client;
use \Vinteract\Utils;

use \Illuminate\Database\Eloquent\Model;

use DateTime;

class UserDevice extends Model {
	
	/*
		Properties
	*/
	
	public $timestamps = false;
	
	protected $hidden = ["pivot"];
	
	protected $visible = [
		"uuid",
		"token",
		"device_id",
		"platform",
		"model",
		"meta",
	];
	
	protected $fillable = [
		"user_id",
		"token",
		"device_id",
		"platform",
		"model",
	];
	
	protected $appends = [
		"meta",
	];
	
	/*
		Overrides
	*/
	
	public function __construct($attributes = []) {
		
		parent::__construct($attributes);
		
		$this->setTable(Client::getName() . "_users_devices");
		$this->setConnection(Client::getType());
		
	}
	
	protected static function boot() {
		
		parent::boot();
		
		static::setEventDispatcher(new \Illuminate\Events\Dispatcher());
		
		static::creating(function($model) {
			$model->uuid = Utils::generateUuid();
			$model->added = (new DateTime())->format("Y-m-d");
		});
		
	}
	
	/*
		Mutators
	*/
	
	public function getMetaAttribute() {
		return array_column(\Vinteract\Client::local("users_devices_meta")->whereDeviceId($this->id)->select(["key", "value"])->get()->toArray(), "value", "key");
	}
	
}