#include <libmegapixels.h>
#include <stdio.h>
#include <limits.h>
#include <getopt.h>
#include <ctype.h>

int
main(int argc, char *argv[])
{
	int c;

	char configpath[PATH_MAX];
	int ret;
	int verbose = 0;

	while ((c = getopt(argc, argv, "c:v")) != -1) {
		switch (c) {
			case 'c':
				sprintf(configpath, "%s", optarg);
				ret = 1;
				break;
			case 'v':
				verbose = 1;
				break;
			case '?':
				if (optopt == 'd' || optopt == 'l') {
					fprintf(stderr, "Option -%c requires an argument.\n", optopt);
				} else if (isprint(optopt)) {
					fprintf(stderr, "Unknown option '-%c'\n", optopt);
				} else {
					fprintf(stderr, "Unknown option character x%x\n", optopt);
				}
				return 1;
			default:
				return 1;
		}
	}
	ret = libmegapixels_find_config_verbose(PATH_MAX, configpath, verbose);
	libmegapixels_devconfig *config = {0};
	libmegapixels_init(&config);

	if (!ret) {
		printf("No config found\n");
	} else {
		printf("Using config: %s\n", configpath);
		if (!libmegapixels_load_file(config, configpath)) {
			printf("Could not load config\n");
		}
	}

	libmegapixels_load_uvc(config);
	if (config->count == 0) {
		return 1;
	}

	printf("Device: %s %s\n", config->make, config->model);
	printf("Found %d cameras\n", config->count);

	for (int i = 0; i < config->count; i++) {
		printf("\n----[ Camera %s (%d) ]----\n", config->cameras[i]->name, config->cameras[i]->index);
		if (config->cameras[i]->bridge_name) {
			printf("Media : %s (%s)\n", config->cameras[i]->bridge_name, config->cameras[i]->media_path);
		}
		if (config->cameras[i]->sensor_name) {
			printf("Sensor: %s (%s)\n", config->cameras[i]->sensor_name, config->cameras[i]->sensor_path);
		}
		printf("Video : %s\n", config->cameras[i]->video_path);
		if (config->cameras[i]->flash_type == LIBMEGAPIXELS_FLASH_SCREEN) {
			printf("Flash : screen\n");
		} else {
			if (config->cameras[i]->flash_path) {
				switch (config->cameras[i]->flash_type) {
					case LIBMEGAPIXELS_FLASH_LED:
						printf("Flash : LED (%s)\n", config->cameras[i]->flash_path);
						break;
					case LIBMEGAPIXELS_FLASH_V4L:
						printf("Flash : V4L flash entity (%s)\n", config->cameras[i]->flash_path);
						break;
				}
			}
		}
		if (config->cameras[i]->lens_path) {
			printf("Focus : %s\n", config->cameras[i]->lens_path);
		}
		printf("Modes : ");
		for (int j = 0; j < config->cameras[i]->num_modes; j++) {
			if (j > 0) {
				printf("        ");
			}
			libmegapixels_mode *mode = config->cameras[i]->modes[j];

			printf("%dx%d@%d [%s]\n", mode->width, mode->height, mode->rate, libmegapixels_format_name(mode->format));
		}
	}
	return 0;
}