<?php

namespace SHServ\Entities;

use \SHServ\Entities\DeviceAuth;
use \SHServ\Entities\Area;
use \SHServ\Tools\DeviceAPI\Base;
use \SHServ\Tools\DeviceAPI\Relay;
use \SHServ\Tools\DeviceAPI\Button;

class Device extends \SHServ\Middleware\Entity {
	public static $table_name = "devices";
	protected static $fields = [
		"id", "area_id", "alias", "name", "device_type", "device_name", "device_ip",
		"device_mac", "device_hard_id", "firmware_version", "connection_state", 
		"state", "description", "last_contact", "create_at", "update_at"
	];

	protected $device_auth_instance;
	protected $device_api_instance;

	public function __construct(Int $id, Array $data = []){
		parent::__construct(
			self::$table_name,
			$id,
			$data
		);	
	}

	public function remove() {
		$this -> state = "removed";
		return $this -> update();
	}

	public function auth(): DeviceAuth | null {
		if($this -> device_auth_instance) {
			return $this -> device_auth_instance;
		}

		$result = app() -> thin_builder -> select(
			DeviceAuth::$table_name, 
			DeviceAuth::get_fields(), 
			[ ["device_id", "=", $this -> id()] ]
		);

		if(!$result) {
			return null;
		}

		$this -> device_auth_instance = new DeviceAuth($result[0]["id"], $result[0]);

		return $this -> device_auth_instance ?? null;
	}

	public function device_api(): ?Base {
		if($this -> device_api_instance) {
			return $this -> device_api_instance;
		}

		switch($this -> device_type) {
			case "relay": 
				$this -> device_api_instance = new Relay($this -> device_ip);
				break;
			case "button": 
				$this -> device_api_instance = new Button($this -> device_ip);
				break;
			default: 
				$this -> device_api_instance = new Base($this -> device_ip);
		}

		if($this -> auth()) {
			$this -> device_api_instance -> set_local_token($this -> auth() -> device_token);
		}

		return $this -> device_api_instance ?? null;
	}

	public function set_device_token(String $token) {
		$this -> device_api() -> remote_set_token($token);
		if(!$this -> auth()) 
			return false;


		$this -> auth() -> device_token = $token;
		$this -> device_api_instance -> set_local_token($token);
		return $this -> auth() -> update();
	}

	public function place_in_area(int $area_id): bool {
		$this -> area_id = $area_id;
		return $this -> update() ? true : false;
	}

	public function get_parent_area(): Area | null {
		if(!$this -> area_id) {
			return null;
		}

		return new Area($this -> area_id);
	}
}