<?php

namespace SHServ\Models;

use \SHServ\Entities\Area;

class Areas extends \SHServ\Middleware\Model {
	private const MAX_LIMIT = 1000;

	public function create_new_area(String $type, String $alias, String $display_name): Area | null {
		if(!$this -> alias_is_uniq($alias)) {
			return null;
		}

		$area_id = app() -> thin_builder -> insert(Area::$table_name, [
			"alias" => $alias,
			"display_name" => $display_name,
			"type" => $type,
			"schema" => "",
			"parent_id" => "0",
			"create_at" => date("Y-m-d H:i:s")
		]);

		return $area_id ? new Area($area_id) : null;
	}

	public function alias_is_uniq(String $alias, ?int $exclude_id = null): bool {
		$where = [ ["alias", "=", $alias] ];
		if ($exclude_id !== null) {
			$where[] = "AND";
			$where[] = ["id", "!=", $exclude_id];
		}

		$count = app() -> thin_builder -> count(
			Area::$table_name,
			$where
		);

		return $count ? false : true;
	}

	public function get_exists_types(): Array {
		$areas = app() -> thin_builder -> select( Area::$table_name, [ "type" ], [] );
		if(!$areas) {
			return [];
		}

		$types = array_map(function($area) { 
			return $area["type"];
		}, $areas);

		$uniq_types = [];

		foreach($types as $type) {
			if(in_array($type, $uniq_types)) {
				continue;
			}

			$uniq_types[] = $type;
		}

		return $uniq_types;
	}

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

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

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

		return $areas;
	}

	public function get_area_by_alias(String $alias): Area | null {
		$raw_area = app() -> thin_builder -> select(
			Area::$table_name,
			Area::get_fields(),
			[[ "alias", "=", $alias ]],
			[], "DESC", [ 1 ]
		);

		return $raw_area ? new Area($raw_area[0]["id"], $raw_area[0]) : null;
	}

	public function get_all(): Array {
		$raw_areas = $this -> thin_builder() -> select(
			Area::$table_name,
			Area::get_fields(),
			[],
			[], "DESC", [ self::MAX_LIMIT ]
		);

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

		return $areas;
	}

}