// Test the new camera functionality
var camera = use('camera');

// Get camera drivers
var drivers = camera.drivers();
log.console("Available camera drivers:", drivers);

// Get list of cameras
var cameras = camera.list();
log.console("Found", length(cameras), "cameras");

// Get info about each camera
var i = 0;
var j = 0;
var cam_id = null;
var formats = null;
var fmt = null;
var preferred_format = null;
var cam = null;
var actual_format = null;

for (i = 0; i < length(cameras); i++) {
  cam_id = cameras[i];
  log.console("\nCamera", i + 1, "ID:", cam_id);
  log.console("  Name:", camera.name(cam_id));
  log.console("  Position:", camera.position(cam_id));

  // Get supported formats
  formats = camera.supported_formats(cam_id);
  log.console("  Supported formats:", length(formats));

  // Show first few formats
  for (j = 0; j < length(formats); j++) {
    fmt = formats[j];
    log.console("    Format", j + 1 + ":");
    log.console("      Pixel format:", fmt.format);
    log.console("      Resolution:", fmt.width + "x" + fmt.height);
    log.console("      FPS:", fmt.framerate_numerator + "/" + fmt.framerate_denominator,
                "(" + (fmt.framerate_numerator / fmt.framerate_denominator) + ")");
    log.console("      Colorspace:", fmt.colorspace);
  }
}

// Open the first camera with a specific format if available
if (length(cameras) > 0) {
  log.console("\nOpening first camera...");
  cam_id = cameras[0];
  formats = camera.supported_formats(cam_id);

  // Try to find a 640x480 format
  preferred_format = null;
  for (i = 0; i < length(formats); i++) {
    if (formats[i].width == 640 && formats[i].height == 480) {
      preferred_format = formats[i];
      break;
    }
  }

  cam = null;
  if (preferred_format) {
    log.console("Opening with 640x480 format...");
    cam = camera.open(cam_id, preferred_format);
  } else {
    log.console("Opening with default format...");
    cam = camera.open(cam_id);
  }

  if (cam) {
    log.console("Camera opened successfully!");
    log.console("Driver being used:", cam.get_driver());

    // Get the actual format being used
    actual_format = cam.get_format();
    log.console("Actual format being used:");
    log.console("  Pixel format:", actual_format.format);
    log.console("  Resolution:", actual_format.width + "x" + actual_format.height);
    log.console("  FPS:", actual_format.framerate_numerator + "/" + actual_format.framerate_denominator,
                "(" + (actual_format.framerate_numerator / actual_format.framerate_denominator) + ")");
    log.console("  Colorspace:", actual_format.colorspace);

    // Clean up - camera will be closed when object is freed
    cam = null;
  }
}
