#ifndef __Fields_H__
#define __Fields_H__
#include"pmc_types.h"
#include"CRemoteLog.h"
template <short MAX_SIZE>
class Fields {
private:
	char fields[MAX_SIZE][MAX_NAME_LEN];
	void zipSpace(char* str) {
		int i = 0;
		int j = 0;
		while (str[i] != '\0') {
			if (str[i] != ' ' && str[i] != '\t') {
				if (i != j) {
					str[j] = str[i];
				}
				j++;
			}
			
			i++;
		}
		str[j] = '\0';
	}
public:
	short length;
	short size() {
		return length;
	}
	Fields() {
		memset(&fields, '\0', sizeof(fields));
		length = 0;
	}
	void clear() {
		memset(&fields, '\0', sizeof(fields));
		length = 0;
	}
	void parse(const char* src, char split) {
		int pos1 = 0;
		int pos2 = 0;
		length = 0;
		clear();
		if (src == NULL) {
			return;
		}
		PMCBOOL breakFlag = FALSE;
		while (!breakFlag) {
			if (src[pos2] == 0) {
				breakFlag = TRUE;
			}
			if (src[pos2] == split || src[pos2] == '\0') {
				if (pos2 - pos1 >= MAX_NAME_LEN) {
					logger->info("String fields too long:[%s]", src);
					return;
				}
				if (length >= MAX_SIZE) {
					logger->info("String fields too more:[%s]", src);
					return;
				}
				memcpy(fields[length], src + pos1, pos2 - pos1);
				fields[length][pos2 - pos1] = '\0';
				
				pos1 = pos2+1;
				
				//zipSpace(fields[length]);
				length++;
				
			}
			pos2++;
		}
	}
	char* get(short index) {
		if (index < 0 || index >= length) {
			return NULL;
		}
		return fields[index];
	}
#ifdef _DEBUG
	char* getValue(const char* key,const char* file=__FILE__,int line=__LINE__) {
		size_t keyLen = strlen(key);
		if (keyLen >= MAX_NAME_LEN - 1) {
			return NULL;
		}
		static char keyEqual[MAX_NAME_LEN];
		strcpy_debug(keyEqual, key,sizeof(keyEqual),file,line);
		strcat(keyEqual, "=");
		for (int i = 0; i < length; i++) {
			if (strncmp(keyEqual, fields[i], keyLen + 1) == 0) {
				return fields[i] + keyLen + 1;
			}
		}
		return NULL;
	}
#else
	char* getValue(const char* key) {
		size_t keyLen = strlen(key);
		if (keyLen >= MAX_NAME_LEN - 1) {
			return NULL;
		}
		static char keyEqual[MAX_NAME_LEN];
		strcpy(keyEqual, key);
		strcat(keyEqual, "=");
		for (int i = 0; i < length; i++) {
			if (strncmp(keyEqual, fields[i], keyLen + 1) == 0) {
				return fields[i] + keyLen + 1;
			}
		}
		return NULL;
	}
#endif
};
#endif