<?php

namespace SHServ\Entities;

use \SHServ\Entities\Device;

class Area extends \SHServ\Middleware\Entity {
	public static $table_name = "areas";
	protected static $fields = [
		"id", "alias", "display_name", "type", 
		"parent_id", "schema", "create_at", "update_at"
	];

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

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

	public function get_inner_areas(): Array {
		$raw_areas = app() -> thin_builder -> select(
			self::$table_name,
			self::get_fields(),
			[[ "parent_id", "=", $this -> id() ]]
		);

		if(!$raw_areas) {
			return [];
		}

		$areas = [];

		foreach($raw_areas as $i => $raw_area) {
			$areas[] = new Area($raw_area["id"], $raw_area);
		}

		return $area;
	}

	public function place_in_area(int $area_id): Array | bool {
		$this -> parent_id = $area_id;
		return $this -> update();
	}

	public function get_areas_by_type(String $type): Array {
		$raw_areas = app() -> thin_builder -> select(
			self::$table_name,
			self::get_fields(),
			[
				[ "parent_id", "=", $this -> id() ], 
				"AND", 
				[ "type", "=", $type ]
			]
		);

		if(!$raw_areas) {
			return [];
		}

		$areas = [];

		foreach($raw_areas as $i => $raw_area) {
			$areas[] = new Area($raw_area["id"], $raw_area);
		}

		return $area;
	}

	public function get_area_by_alias(): Area | null {
		$raw_areas = app() -> thin_builder -> select(
			self::$table_name,
			self::get_fields(),
			[
				[ "parent_id", "=", $this -> id() ], 
				"AND", 
				[ "alias", "=", $alias ]
			],
			[], "DESC",
			[ 1 ]
		);

		if(!$raw_areas) {
			return null;
		}

		return new Area($raw_areas[0]["id"], $raw_areas[0]);
	}

	public function get_inner_devices(): Array {
		$raw_devices = app() -> thin_builder -> select(
			Device::$table_name,
			Device::get_fields(),
			[["area_id", "=", $this -> id()]]
		);

		if(!$raw_devices) {
			return [];
		}

		$devices = [];
		foreach($raw_devices as $raw_device) {
			$devices[] = new Device($raw_device["id"], $raw_device);
		}

		return $devices;
	}

	public function get_device_by_alias(string $alias): Device | null {
		$raw_devices = app() -> thin_builder -> select(
			Device::$table_name,
			Device::get_fields(),
			[
				[ "area_id", "=", $this -> id() ],
				"AND", 
				[ "alias", "=", $alias ]
			],
			[], "DESC", 
			[ 1 ]
		);

		if(!$raw_devices) {
			return null;
		}

		$raw_device = $raw_devices[0];
		return new Device($raw_device["id"], $raw_device);
	}

	public function get_devices_by_type(string $type): Array {
		$raw_devices = app() -> thin_builder -> select(
			Device::$table_name,
			Device::get_fields(),
			[
				[ "area_id", "=", $this -> id() ],
				"=",
				[ "type", "=", $type ] 
			]
		);

		if(!$raw_devices) {
			return [];
		}

		$devices = [];
		foreach($raw_devices as $raw_device) {
			$devices[] = new Device($raw_device["id"], $raw_device);
		}

		return $devices;
	}
}