#include "XCCom.h"
#include "utils.h"

wchar_t *error_msg[] = {
	L"Unknown XCircuit error",
	L"Trying to access/modify an invalid XCircuit object",
	L"The specified color index is out of range",
	L"The arc object is not a circle",
	L"Invalid arc angles specification: stop angle must be greater than start angle",
	L"Invalid border specification",
	L"Index out of range",
	L"Invalid number of arguments",
	L"Invalid text justification specification",
};

int get_string_index(BSTR val, char **sarray, int ssize)
{
	int i=0, n;
	char *buf;

	n = wcslen(val);
	buf = (char*)malloc(sizeof(char)*2*n);
	memset(buf, 0, sizeof(char)*2*n);
	wcstombs(buf, val, n);
	for (i=0; i<ssize; i++)
		if (strcmp(buf, sarray[i]) == 0)
			break;
	free(buf);
	return (i<ssize ? i : -1);
}

int get_string_index_from_variant(VARIANT *val, char **sarray, int ssize)
{
	if (val->vt != VT_BSTR)
		return -1;
	return get_string_index(val->bstrVal, sarray, ssize);
}

int get_wide_string_index(BSTR val, wchar_t **sarray, int ssize)
{
	int i;

	for (i=0; i<ssize; i++)
		if (wcscmp(val, sarray[i]) == 0)
			return i;
	return -1;
}

char* convert_from_bstr(BSTR val)
{
	int len;
	char *str;

	len = wcslen(val);
	str = (char*)malloc(sizeof(char)*(len+1));
	wcstombs(str, val, len+1);

	return str;
}

BSTR convert_to_bstr(char *str)
{
	wchar_t *wstr;
	int len;
	BSTR bstr;

	len = strlen(str);
	wstr = (wchar_t*)malloc(sizeof(wchar_t)*(len+1));
	mbstowcs(wstr, str, len+1);
	bstr = SysAllocString(wstr);
	free(wstr);

	return bstr;
}

char *string_from_parts(stringpart *parts)
{
	char *str = (char*)malloc(sizeof(char)*1);

	str[0] = '\0';
	for (; parts != NULL; parts=parts->nextpart) {
		switch (parts->type) {
			case TEXT_STRING:
				str = (char*)realloc(str, strlen(str)+strlen(parts->data.string)+1);
				strcat(str, parts->data.string);
				break;
			default:
				break;
		}
	}

	return str;
}

stringpart *string_to_parts(char *str)
{
	int p1 = 0, p2;
	stringpart *part = NULL, **nextpart = &part;
	int type = -1;
	char *data = NULL;

	for (p2=0; p1>=0; p2++) {
		switch (str[p2]) {
			case '\0':
				type = TEXT_STRING;
				data = strdup(str+p1);
				p1 = -1;
				break;
		}
		if (type >= 0) {
			*nextpart = (stringpart*)malloc(sizeof(stringpart));
			(*nextpart)->type = type;
			(*nextpart)->data.string = data;
			(*nextpart)->nextpart = NULL;
			nextpart = &((*nextpart)->nextpart);
		}
	}

	return part;
}
