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

// Get list of cameras
var cameras = camera.list();
if (cameras.length == 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 < formats.length; i++) {
  var fmt = formats[i];
  if (!colorspaces[fmt.colorspace]) {
    colorspaces[fmt.colorspace] = [];
  }
  colorspaces[fmt.colorspace].push(fmt);
}

log.console("\nFound colorspaces:");
for (var cs in colorspaces) {
  log.console("  " + cs + ": " + colorspaces[cs].length + " formats");
}

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

for (var cs in colorspaces) {
  // 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 (Object.keys(colorspaces).indexOf(cs) >= 2) break;
}

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