
#include "ced.h"
#include "cu.h"
#include "c_clan.h"
#import "DatasetBoxController.h"

extern NSFont *defUniFont;

struct label_cols {
	char *label;
	int  num;
	struct label_cols *next_label;
};
static struct label_cols *datasets;

@implementation DatasetBoxController

- (id)init {
	return [super initWithWindowNibName:@"DatasetBox"];
}

static struct label_cols *freeLabels(struct label_cols *p) {
	struct label_cols *t;

	while (p != NULL) {
		t = p;
		p = p->next_label;
		if (t->label)
			free(t->label);
		free(t);
	}
	return(NULL);
}

static struct label_cols *addDSToList(label_cols *root, char *label) {
	struct label_cols *ts;

	if (root == NULL) {
		root = NEW(struct label_cols);
		ts = root;
	} else {
		for (ts=root; ts->next_label != NULL; ts=ts->next_label) {
			if (uS.mStricmp(ts->label, label) == 0)
				return(root);
		}
		if (uS.mStricmp(ts->label, label) == 0)
			return(root);
		ts->next_label = NEW(struct label_cols);
		ts = ts->next_label;
	}
	if (ts == NULL) {
		root = freeLabels(root);
	}
	ts->next_label = NULL;
	ts->label = (char *)malloc(strlen(label)+1);
	if (ts->label == NULL) {
		root = freeLabels(root);
	}
//	uS.lowercasestr(label, &dFnt, C_MBF);
	strcpy(ts->label, label);
	return(root);
}

static void listDatasets(char *f) {
	char *b, *e;
	char ds_name[128], ds_nameo[512], name[128], ds_age[64], age[64];
	char ds_activity[128], ds_activityo[128], activity[128];
	int cnt, agef, aget, ds_agef, ds_aget;
	FILE *fp;

	datasets = NULL;
	strcpy(FileName1, lib_dir);
	addFilename2Path(FileName1, "kideval");
	addFilename2Path(FileName1, "0refvals.csv");
	fp = fopen(FileName1, "r");
	if (fp == NULL) {
		strcpy(FileName1, wd_dir);
		addFilename2Path(FileName1, "0refvals.csv");
		fp = fopen(FileName1, "r");
	}
	if (fp == NULL) {
		return;
	}

	name[0] = EOS;
	age[0] = EOS;
	activity[0] = EOS;
	agef = 0;
	aget = 0;
	b = f;
	while (b != NULL) {
		e = strchr(b, '~');
		if (e != NULL) {
			*e = EOS;
			if (b == f) {
				if (isdigit(*b) && (isdigit(*(b+1)) || *(b+1) == ';' ||  *(b+1) == '.' ||  *(b+1) == '-' ||  *(b+1) == EOS)) {
					strncpy(age, b, 62);
					age[62] = EOS;
				} else {
					strncpy(name, b, 126);
					name[126] = EOS;
					uS.lowercasestr(name, &dFnt, MBF);
				}
			} else if (isdigit(*b)) {
				strncpy(age, b, 62);
				age[62] = EOS;
			} else {
				strncpy(activity, b, 126);
				activity[126] = EOS;
				uS.lowercasestr(activity, &dFnt, MBF);
			}
			*e = '~';
			b = e + 1;
		} else {
			if (b == f) {
				if (isdigit(*b) && (isdigit(*(b+1)) || *(b+1) == ';' ||  *(b+1) == '.' ||  *(b+1) == '-' ||  *(b+1) == EOS)) {
					strncpy(age, b, 62);
					age[62] = EOS;
				} else {
					strncpy(name, b, 126);
					name[126] = EOS;
					uS.lowercasestr(name, &dFnt, MBF);
				}
			} else if (isdigit(*b)) {
				strncpy(age, b, 62);
				age[62] = EOS;
			} else {
				strncpy(activity, b, 126);
				activity[126] = EOS;
				uS.lowercasestr(activity, &dFnt, MBF);
			}
			b = NULL;
		}
	}
	if (age[0] != EOS) {
		if (isAge(age, &agef, &aget) == FALSE) {
			return;
		}
	}
	datasets = NULL;
	if (!fgets_cr(templineC4, BUFSIZ, fp))
		return;
	while (fgets_cr(templineC4, BUFSIZ, fp)) {
		if (uS.isUTF8(templineC4) || uS.isInvisibleHeader(templineC4))
			continue;
		ds_name[0] = EOS;
		ds_nameo[0] = EOS;
		uS.remblanks(templineC4);
		b = templineC4;
		cnt = 0;
		while (b != NULL) {
			e = strchr(b, ',');
			if (e != NULL) {
				*e = EOS;
				cnt++;
				if (cnt == 3) {
					strncpy(ds_nameo, b, 510);
					ds_nameo[510] = EOS;
					strncpy(ds_name, b, 126);
					ds_name[126] = EOS;
					uS.lowercasestr(ds_name, &dFnt, MBF);
				} else if (cnt == 5) {
					strncpy(ds_age, b, 62);
					ds_age[62] = EOS;
					isAge(ds_age, &ds_agef, &ds_aget);
				} else if (cnt == 14) {
					strncpy(ds_activityo, b, 126);
					ds_activityo[126] = EOS;
					strncpy(ds_activity, b, 126);
					ds_activity[126] = EOS;
					uS.lowercasestr(ds_activity, &dFnt, MBF);
					*e = ',';
					if (name[0] == EOS || uS.fpatmat(ds_name, name) == 1) {
						if ((agef == 0 && aget == 0) ||
							(aget == 0 && agef >= ds_agef && agef <= ds_aget) ||
							(agef == ds_agef && aget == ds_aget)) {
							if (activity[0] == EOS || uS.fpatmat(ds_activity, activity) == 1) {
								strcat(ds_nameo, "~");
								strcat(ds_nameo, ds_age);
								strcat(ds_nameo, "    ");
								strcat(ds_nameo, ds_activityo);
								datasets = addDSToList(datasets, ds_nameo);
							}
						}
					}
					break;
				}
				*e = ',';
				b = e + 1;
			} else {
				cnt++;
				if (cnt == 3) {
					strncpy(ds_nameo, b, 510);
					ds_nameo[510] = EOS;
					strncpy(ds_name, b, 126);
					ds_name[126] = EOS;
					uS.lowercasestr(ds_name, &dFnt, MBF);
				} else if (cnt == 5) {
					strncpy(ds_age, b, 62);
					ds_age[62] = EOS;
					isAge(ds_age, &ds_agef, &ds_aget);
				} else if (cnt == 14) {
					strncpy(ds_activity, b, 126);
					ds_activity[126] = EOS;
					uS.lowercasestr(ds_activity, &dFnt, MBF);
					if (name[0] == EOS || uS.fpatmat(ds_name, name) == 1) {
						if ((agef == 0 && aget == 0) ||
							(aget == 0 && agef >= ds_agef && agef <= ds_aget) ||
							(agef == ds_agef && aget == ds_aget)) {
							if (activity[0] == EOS || uS.fpatmat(ds_activity, activity) == 1) {
								strcat(ds_nameo, "~");
								strcat(ds_nameo, ds_age);
								strcat(ds_nameo, "    ");
								strcat(ds_nameo, ds_activityo);
								datasets = addDSToList(datasets, ds_nameo);
							}
						}
					}
					break;
				}
				b = NULL;
			}
		}
	}
	fclose(fp);
}

- (IBAction)datasetTableClicked:(id)sender
{
/*
 	int  i, j, len;
	char datasetNum[256];
	NSString *datasetName, *str;
	NSDictionary *addedObject;
	NSIndexSet *range;

#pragma unused (sender)

	NSLog(@"DatasetBoxController: datasetTableClicked\n");

	len = [[datasetSelArray arrangedObjects] count];
	if (len > 0) {
		range = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, len)];
		[datasetSelArray removeObjectsAtArrangedObjectIndexes:range];
	}

	sDatasets = [datasetTableArray selectedObjects];
	len = [sDatasets count];
	for (i=0; i < len; i++) {
		datasetName = (NSString *)[[self->sDatasets objectAtIndex:i] objectForKey:@"lines"];
		strcpy(templineC2, [datasetName UTF8String]);
		for (j=0; j < strlen(templineC2) && templineC2[j] != ':'; j++) ;
		if (templineC2[j] == ':')
			templineC2[j] = EOS;
		strcpy(datasetNum, templineC2);
		str = [NSString stringWithUTF8String:datasetNum];
		addedObject = [NSDictionary dictionaryWithObjectsAndKeys:str, @"lines", nil];
		[datasetSelArray addObject:addedObject];

	}
	[datasetSelArray removeSelectionIndexes:[datasetSelArray selectionIndexes]];
*/
}


- (void)windowDidLoad {
	int cnt;
	NSUInteger len;
//	NSUInteger num;
	CGSize textSize;
	NSDictionary *addedObject, *attributes;
	NSString *str;
	NSWindow *window = [self window];
	NSIndexSet *range;
	char datasetName[256];
	struct label_cols *ts;

	[window setIdentifier:@"DatasetBox"];
	[super windowDidLoad];  // It's documented to do nothing, but still a good idea to invoke...
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:) name:NSWindowWillCloseNotification object:self.window];
//	datasetTableView.doubleAction = @selector(doubleClick:);

	len = [[datasetSelArray arrangedObjects] count];
	if (len > 0) {
		range = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, len)];
		[datasetSelArray removeObjectsAtArrangedObjectIndexes:range];
	}
	attributes = @{NSFontAttributeName:defUniFont};
	sDatasets = nil;
	datasets = NULL;
	listDatasets(self->datasetArg);
	len = 0;
	cnt = 0;
	if (datasets != NULL) {
		for (ts=datasets; ts != NULL; ts=ts->next_label) {
			cnt++;
			sprintf(datasetName, "#%2d: ", cnt);
			strcat(datasetName, ts->label);
			str = [NSString stringWithUTF8String:datasetName];
			addedObject = [NSDictionary dictionaryWithObjectsAndKeys:str, @"lines", nil];
			if (addedObject != nil) {
				textSize = [[addedObject valueForKey:@"lines"] sizeWithAttributes:attributes];
				if (len < textSize.width)
					len = textSize.width;
				[datasetTableArray addObject:addedObject];
			}
		}
	}
	if (len > 0 && len < 5000)
		datasetTableView.tableColumns[0].width = len;
//	num = [[datasetTableArray arrangedObjects] count];
//	if (cnt < num)
//		[datasetTableArray setSelectionIndex:cnt];
	[datasetTableArray removeSelectionIndexes:[datasetTableArray selectionIndexes]];
	if (datasets != NULL)
		datasets = freeLabels(datasets);
}

- (void)windowWillClose:(NSNotification *)notification {
#pragma unused (notification)
	sDatasets = [datasetTableArray selectedObjects];
	NSLog(@"DatasetBoxController: windowWillClose\n");
	[[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowWillCloseNotification object:self.window];

}

/* Reopen the line panel when the app's persistent state is restored.
 */
+ (void)restoreWindowWithIdentifier:(NSString *)identifier state:(NSCoder *)state completionHandler:(void (^)(NSWindow *, NSError *))completionHandler {
	//    completionHandler([[(Controller *)[NSApp delegate] listBoxController] window], NULL);
}

@end

@implementation DatasetBoxController(Delegation)

- (void)tableViewSelectionDidChange:(NSNotification *)notification {
#pragma unused (notification)
//	NSUInteger row;

	NSLog(@"DatasetBoxController: tableViewSelectionDidChange\n");

	int	 i, len;
	char *s;
	NSString *datasetName, *str;
	NSDictionary *addedObject;
	NSIndexSet *range;
	NSTableView *cTableView;


	cTableView = [notification object];
	if (cTableView == datasetTableView) {
		len = [[datasetSelArray arrangedObjects] count];
		if (len > 0) {
			range = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, len)];
			[datasetSelArray removeObjectsAtArrangedObjectIndexes:range];
		}
		
		sDatasets = [datasetTableArray selectedObjects];
		len = [sDatasets count];
		for (i=0; i < len; i++) {
			datasetName = (NSString *)[[self->sDatasets objectAtIndex:i] objectForKey:@"lines"];
			strcpy(templineC2, [datasetName UTF8String]);
			s = strchr(templineC2, ':');
			if (s != NULL)
				*s = EOS;
			str = [NSString stringWithUTF8String:templineC2];
			addedObject = [NSDictionary dictionaryWithObjectsAndKeys:str, @"lines", nil];
			[datasetSelArray addObject:addedObject];
			
		}
		[datasetSelArray removeSelectionIndexes:[datasetSelArray selectionIndexes]];
	}


//	cTableView = [notification object];
//	row = [datasetTableArray selectionIndex];
//	clickedRow = [datasetTableView clickedRow];
//	clickedColumn = [datasetTableView clickedColumn];


}

@end
