<?php

const SERVICE_DB_SETTING_FILE = "./../../server/setup/service_db_setting.php";
$has_file = file_exists(SERVICE_DB_SETTING_FILE);
if ($has_file) {
	include(SERVICE_DB_SETTING_FILE);
}

class DBConnector
{
	private $mysqli, $stmt, $query, $paramTypeList, $paramValueArray;
	private $db_host, $db_user, $db_passwd, $db_name;

	function __construct()
	{
		global $db_host, $db_user, $db_passwd, $db_name;

		$this->stmt = null;
		$this->paramTypeList = "";
		$this->paramValueArray = null;

		if (isset($db_host) && $db_host !== null) {
			$this->db_host = $db_host;
			$this->db_user = $db_user;
			$this->db_passwd = $db_passwd;
			$this->db_name = $db_name;
		} else {
			$this->db_host = "localhost";
			$this->db_user = "chocomae";
			$this->db_passwd = "sEobMPuJ2A8KTfwU";
			$this->db_name = "chocomae";
		}
	}

	function __destruct()
	{
	}

	public function connectDB()
	{
		// connect db
		$this->mysqli = new mysqli($this->db_host, $this->db_user, $this->db_passwd, $this->db_name);
		// if ($this->mysqli->connect_error) {
		if (mysqli_connect_errno()) {
			return false;
		}

		$query = "USE chocomae";
		$result = $this->mysqli->query($query);
		if (!$result) {
			return false;
		}

		return true;
	}

	public function closeDB()
	{
		if (isset($this->mysqli) || $this->mysqli === null) {
			return;
		}

		if ($this->mysqli->connect_error) {
			$this->mysqli->close();
		}
	}

	public function getDBVariables()
	{
		$variables = array();
		$variables["host"] = $this->db_host;
		$variables["user"] = $this->db_user;
		$variables["passwd"] = $this->db_passwd;
		$variables["name"] = $this->db_name;
		return $variables;
	}

	public function getMysqli()
	{
		return $this->mysqli;
	}
}
?>