<?php

namespace SHServ\Factory;

use \SHServ\Entities\User;
use \SHServ\Entities\Profile;
use \SHServ\Entities\Session;
use \SHServ\Entities\Meta;

class Getter {
	public function get_user_by(String $field_name, $field_value): ?User {
		$result = app() -> thin_builder -> select(
			User::$table_name, 
			User::get_fields(), 
			[ [$field_name, "=", $field_value] ]
		);

		if(!$result) {
			return null;
		}

		return new User($result[0]["id"], $result[0]);
	}

	public function get_profile_by(String $field_name, $field_value) {
		$result = app() -> thin_builder -> select(
			Profile::$table_name, 
			["id"], 
			[ [$field_name, "=", $field_value] ],
			[], "",
			[0, 1]
		);

		if(!$result) {
			return null;
		}

		return new Profile($result[0]["id"]);
	}

	public function get_session_by(String $field_name, $field_value): ?Session {
		$result = app() -> thin_builder -> select(
			Session::$table_name,
			Session::get_fields(),
			[[$field_name, "=", $field_value]],
			["last_using_at"],
			"DESC",
			[0, 1]
		);

		if(!$result) {
			return null;
		}

		return new Session(intval($result[0]["id"]), $result[0]);
	}

	public function get_meta(Int $ent_id, String $assignment, Int $amount = 10): Array {
		$result = app() -> thin_builder -> select(
			Meta::$table_name,
			Meta::get_fields(),
			[ ["ent_id", "=", $ent_id], "AND", ["assignment", "=", $assignment] ],
			[],
			"",
			[0, $amount]
		);

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

		$meta = [];
		foreach($result as $item) {
			$meta[] = new Meta($item["id"], $item);
		}

		return $meta;
	}
}