#include <cameraIdentity.h>
#include <libcamera/property_ids.h>
#include <algorithm>
#include <cctype>
#include <optional>
#include <string_view>

namespace lcamera_dev {

std::string locationPropertyToLabel(int32_t locationValue)
{
	using namespace libcamera::properties;

	if (locationValue == CameraLocationFront) {
		return "front";
	}
	if (locationValue == CameraLocationBack) {
		return "back";
	}
	if (locationValue == CameraLocationExternal) {
		return "external";
	}

	return "";
}

CameraIdentityRecord buildIdentityRecord(
	const std::shared_ptr<libcamera::Camera>& camera)
{
	CameraIdentityRecord record;
	record.id = camera->id();

	const libcamera::ControlList& props = camera->properties();

	const std::optional<std::string_view> model =
		props.get(libcamera::properties::Model);
	if (model) {
		record.model.assign(model->begin(), model->end());
	}

	const std::optional<int> location =
		props.get(libcamera::properties::Location);
	if (location)
	{
		record.locationLabel = locationPropertyToLabel(*location);
	}

	return record;
}

std::vector<CameraIdentityRecord> buildIdentityRecords(
	const std::vector<std::shared_ptr<libcamera::Camera>>& cameras)
{
	std::vector<CameraIdentityRecord> records;
	records.reserve(cameras.size());

	for (const auto& camera : cameras)
	{
		if (!camera) { continue; }

		records.push_back(buildIdentityRecord(camera));
	}

	return records;
}

} // namespace lcamera_dev
