// Test camera colorspace functionality
var camera = use('camera');
var json = use('json');

// Get list of cameras
var cameras = camera.list();
if (length(cameras) == 0) {
  log.console("No cameras found!");
  $stop();
}

var cam_id = cameras[0];
log.console("Testing camera:", camera.name(cam_id));

// Get supported formats
var formats = camera.supported_formats(cam_id);
log.console("\nLooking for different colorspaces in supported formats...");

// Group formats by colorspace
var colorspaces = {};
for (var i = 0; i < length(formats); i++) {
  var fmt = formats[i];
  if (!colorspaces[fmt.colorspace]) {
    colorspaces[fmt.colorspace] = [];
  }
  push(colorspaces[fmt.colorspace], fmt);
}

log.console("\nFound colorspaces:");
arrfor(array(colorspaces), function(key) {
  log.console("  " + key + ": " + length(colorspaces[key]) + " formats");
})

// Try opening camera with different colorspaces
log.console("\nTrying to open camera with different colorspaces...");

arrfor(array(colorspaces), function(cs) {
  // Get first format for this colorspace
  var format = colorspaces[cs][0];
  
  log.console("\nTrying colorspace '" + cs + "' with format:");
  log.console("  Resolution: " + format.width + "x" + format.height);
  log.console("  Pixel format: " + format.format);
  
  // You can also create a custom format with a specific colorspace
  var custom_format = {
    format: format.format,
    colorspace: cs,  // This will be converted from string
    width: format.width,
    height: format.height,
    framerate_numerator: format.framerate_numerator,
    framerate_denominator: format.framerate_denominator
  };
  
  var cam = camera.open(cam_id, custom_format);
  if (cam) {
    var actual = cam.get_format();
    log.console("  Opened successfully!");
    log.console("  Actual colorspace: " + actual.colorspace);
    
    // Camera will be closed when object is freed
    cam = null;
  } else {
    log.console("  Failed to open with this colorspace");
  }
  
  // Just test first 3 colorspaces
  if (find(array(colorspaces), cs) >= 2) return false
}, null, false)

log.console("\nColorspace test complete!");
$stop();