/* gcc test2.c -o test2 -g `pkg-config --cflags --libs libical` && ./test2 */

#include <libical/ical.h>
#include <stdio.h>
#include <stdlib.h>

static void
icomp_x_prop_set (icalcomponent *comp,
                  const char *key,
                  const char *value)
{
	icalproperty *xprop;

	/* Find the old one first */
	xprop = icalcomponent_get_first_property (comp, ICAL_X_PROPERTY);

	while (xprop) {
		const char *str = icalproperty_get_x_name (xprop);

		if (!strcmp (str, key)) {
			if (value) {
				icalproperty_set_value_from_string (xprop, value, "NO");
			} else {
				icalcomponent_remove_property (comp, xprop);
				icalproperty_free (xprop);
			}
			break;
		}

		xprop = icalcomponent_get_next_property (comp, ICAL_X_PROPERTY);
	}

	if (!xprop && value) {
		xprop = icalproperty_new_x (value);
		icalproperty_set_x_name (xprop, key);
		icalcomponent_add_property (comp, xprop);
	}
}

static char *
icomp_x_prop_get (icalcomponent *comp,
                  const char *key)
{
	icalproperty *xprop;

	/* Find the old one first */
	xprop = icalcomponent_get_first_property (comp, ICAL_X_PROPERTY);

	while (xprop) {
		const char *str = icalproperty_get_x_name (xprop);

		if (!strcmp (str, key)) {
			break;
		}

		xprop = icalcomponent_get_next_property (comp, ICAL_X_PROPERTY);
	}

	if (xprop) {
		return icalproperty_get_value_as_string_r (xprop);
	}

	return NULL;
}

#define KEY "X-TEST-QUOTES"
#define TO_SET "string with \"quotes\" used"

int main (void)
{
	icalcomponent *comp;
	char *prop;

	comp = icalcomponent_new (ICAL_VEVENT_COMPONENT);
	if (!comp) {
		return 1;
	}

	icomp_x_prop_set (comp, KEY, TO_SET);
	prop = icomp_x_prop_get (comp, KEY);

	printf ("set '%s', got '%s', same:%s\n", TO_SET, prop ? prop : NULL, (prop && strcmp (prop, TO_SET) == 0) ? "yes" : "no!!!");

	if (prop)
		free (prop);
	icalcomponent_free (comp);

	return 0;
}
