
#import "DSMAppController.h"
#import <pudobjectmodel/pudobjectmodel.h>
#import <tdviewkit/TDQueryController.h>

@implementation DSMAppController

- awakeFromNib
{
		/* Put the cursor in the first Query field when the app starts */
	[firstTextField selectText:self];

	[checkMarkColumn setFormatter:[[NXImageFormatter alloc] init]];

	dateKeys = [[[NSArray alloc]
initWithObjects:@"INSTALLED_DATE",@"REBATE_FORM_DATE",@"PAYMENT_FORM_DATE",@"CHECK_DATE",@"CHECK_MAILED_DATE",@"INITIAL_CONTACT_DATE",@"QUALIFICATION_DATE",@"AGREEMENT_DATE",@"SIGN_INSTALLED_DATE",@"INSPECTION_DATE",@"PICTURE_DATE",@"ENERGY_LABEL_INSTALLED_DATE",@"PAYMENT_FORM_DATE",@"CERTIFICATE_COMPLETED_DATE",@"WATER_HEATER_REBATE_DATE",@"OWNER_HANDBOOK_SENT_DATE",@"SURVEY_SENT_DATE",@"ZERO_PAYMENT_DATE",@"FIVE_PAYMENT_DATE",@"PACKET_GIVEN_DATE",@"AUDIT_COMPLETED_DATE",@"BID_RECEIVED_DATE",@"BID_APPROVED_DATE",@"LOAN_COMM_ACTION_DATE"@"BOARD_APPROVAL_DATE",@"CREDIT_APPLICATION_DATE",@"CREDIT_APPROVED_DATE",@"APPROVAL_NOTICE_SENT",@"UCC_SIGNED_DATE",@"PAYMENT_FORM_COMPLETED_DATE",@"UCC_FILED_DATE",@"PICTURE_DWELLING_DATE",@"PAYMENT_DATE",@"BOARD_APPROVAL_DATE",@"COMPLETED_DATE",@"ACKNOWLEDGEMENT_SIGNED_DATE",@"HISTORY_FILED_DATE",@"ENERGY_REVIEW_ORDERED",@"ENERGY_REVIEW_RECEIVED",@"ENERGY_REVIEW_CONTRACT",@"PROJECT_CONTRACT",nil] 		retain];
 
	return [super awakeFromNib];
}

- (void)resetMenuCells
{
	[nWaterHeaterCell setEnabled:([[rootController selectedObjects] count] == 1)];
	[dWaterHeaterCell setEnabled:([[waterHeaterEOController selectedObjects] count] == 1)];

	[nWeatherizationCell setEnabled:([[rootController selectedObjects] count] == 1)];
	[dWeatherizationCell setEnabled:([[weatherizationEOController selectedObjects] count] == 1)];

	[nSuperGoodCentsCell setEnabled:([[rootController selectedObjects] count] == 1)];
	[dSuperGoodCentsCell setEnabled:([[superGoodCentsEOController selectedObjects] count] == 1)];

	[nHeatPumpCell setEnabled:([[rootController selectedObjects] count] == 1)];
	[dHeatPumpCell setEnabled:([[heatPumpEOController selectedObjects] count] == 1)];

	[nCommercialLightCell setEnabled:([[rootController selectedObjects] count] == 1)];
	[dCommercialLightCell setEnabled:([[commercialLightEOController selectedObjects] count] == 1)];

	[nInstitutionalCell setEnabled:([[rootController selectedObjects] count] == 1)];
	[dInstitutionalCell setEnabled:([[institutionalEOController selectedObjects] count] == 1)];

	[nIndustrialCell setEnabled:([[rootController selectedObjects] count] == 1)];
	[dIndustrialCell setEnabled:([[industrialEOController selectedObjects] count] == 1)];

	[nMotorCell setEnabled:([[rootController selectedObjects] count] == 1)];
	[dMotorCell setEnabled:([[motorEOController selectedObjects] count] == 1)];

	[nHighBillCell setEnabled:([[rootController selectedObjects] count] == 1)];
	[dHighBillCell setEnabled:([[highBillEOController selectedObjects] count] == 1)];

	[super resetMenuCells];
}

- (void)createConnections
{	
	[nWaterHeaterCell setTarget:waterHeaterEOController];
	[nWaterHeaterCell setAction:@selector(insert:)];
	[dWaterHeaterCell setTarget:waterHeaterEOController];
	[dWaterHeaterCell setAction:@selector(delete:)];
	[showWaterHeaterWindowCell setTarget:waterHeaterWindow];
	[showWaterHeaterWindowCell setAction:@selector(makeKeyAndOrderFront:)];

	[nWeatherizationCell setTarget:weatherizationEOController];
	[nWeatherizationCell setAction:@selector(insert:)];
	[dWeatherizationCell setTarget:weatherizationEOController];
	[dWeatherizationCell setAction:@selector(delete:)];
	[showWeatherizationWindowCell setTarget:weatherizationWindow];
	[showWeatherizationWindowCell setAction:@selector(makeKeyAndOrderFront:)];

	[nSuperGoodCentsCell setTarget:superGoodCentsEOController];
	[nSuperGoodCentsCell setAction:@selector(insert:)];
	[dSuperGoodCentsCell setTarget:superGoodCentsEOController];
	[dSuperGoodCentsCell setAction:@selector(delete:)];
	[showSuperGoodCentsWindowCell setTarget:superGoodCentsWindow];
	[showSuperGoodCentsWindowCell setAction:@selector(makeKeyAndOrderFront:)];


	[nHeatPumpCell setTarget:heatPumpEOController];
	[nHeatPumpCell setAction:@selector(insert:)];
	[dHeatPumpCell setTarget:heatPumpEOController];
	[dHeatPumpCell setAction:@selector(delete:)];
	[showHeatPumpWindowCell setTarget:heatPumpWindow];
	[showHeatPumpWindowCell setAction:@selector(makeKeyAndOrderFront:)];

	[nCommercialLightCell setTarget:commercialLightEOController];
	[nCommercialLightCell setAction:@selector(insert:)];
	[dCommercialLightCell setTarget:commercialLightEOController];
	[dCommercialLightCell setAction:@selector(delete:)];
	[showCommercialLightWindowCell setTarget:commercialLightWindow];
	[showCommercialLightWindowCell setAction:@selector(makeKeyAndOrderFront:)];

	[nInstitutionalCell setTarget:institutionalEOController];
	[nInstitutionalCell setAction:@selector(insert:)];
	[dInstitutionalCell setTarget:institutionalEOController];
	[dInstitutionalCell setAction:@selector(delete:)];
	[showInstitutionalWindowCell setTarget:institutionalWindow];
	[showInstitutionalWindowCell setAction:@selector(makeKeyAndOrderFront:)];


	[nIndustrialCell setTarget:industrialEOController];
	[nIndustrialCell setAction:@selector(insert:)];
	[dIndustrialCell setTarget:industrialEOController];
	[dIndustrialCell setAction:@selector(delete:)];
	[showIndustrialWindowCell setTarget:industrialWindow];
	[showIndustrialWindowCell setAction:@selector(makeKeyAndOrderFront:)];

	[nMotorCell setTarget:motorEOController];
	[nMotorCell setAction:@selector(insert:)];
	[dMotorCell setTarget:motorEOController];
	[dMotorCell setAction:@selector(delete:)];
	[showMotorWindowCell setTarget:motorWindow];
	[showMotorWindowCell setAction:@selector(makeKeyAndOrderFront:)];

	[nHighBillCell setTarget:highBillEOController];
	[nHighBillCell setAction:@selector(insert:)];
	[dHighBillCell setTarget:highBillEOController];
	[dHighBillCell setAction:@selector(delete:)];
	[showHighBillWindowCell setTarget:highBillWindow];
	[showHighBillWindowCell setAction:@selector(makeKeyAndOrderFront:)];


	[super createConnections];
}

- (BOOL)controller:(EOController *)controller 
	willInsertObject:object 
	atIndex:(unsigned int) newIndex
{
	if (controller == waterHeaterEOController) {
		int nextKeyVal = [uniqController uniqueIDForKey:@"water_heater_object_id_maker.nextval"
			tableName:@"water_heater"
			whereClause:@"object_id = 1"];
		id currentAccount = [rootController currentObject];

		[object setObjectID:nextKeyVal];
		[object setParent:currentAccount];
		[object setTI_ACCOUNT_NO:[currentAccount TI_ACCOUNT_NO]];
	}

	else if (controller == weatherizationEOController) {
		int nextKeyVal = [uniqController uniqueIDForKey:@"weatherization_object_id_maker.nextval"
			tableName:@"weatherization"
			whereClause:@"object_id = 1"];
		id currentAccount = [rootController currentObject];

		[object setObjectID:nextKeyVal];
		[object setParent:currentAccount];
		[object setTI_ACCOUNT_NO:[currentAccount TI_ACCOUNT_NO]];
	}

	else if (controller == superGoodCentsEOController) {
		int nextKeyVal = [uniqController uniqueIDForKey:@"sgc_object_id_maker.nextval"
			tableName:@"sgc"
			whereClause:@"object_id = 1"];
		id currentAccount = [rootController currentObject];

		[object setObjectID:nextKeyVal];
		[object setParent:currentAccount];
		[object setTI_ACCOUNT_NO:[currentAccount TI_ACCOUNT_NO]];
	}

	else if (controller == heatPumpEOController) {
		int nextKeyVal = [uniqController uniqueIDForKey:@"heat_pump_object_id_maker.nextval"
			tableName:@"heat_pump"
			whereClause:@"object_id = 1"];
		id currentAccount = [rootController currentObject];

		[object setObjectID:nextKeyVal];
		[object setParent:currentAccount];
		[object setTI_ACCOUNT_NO:[currentAccount TI_ACCOUNT_NO]];
	}


	else if (controller == commercialLightEOController) {
		int nextKeyVal = [uniqController uniqueIDForKey:@"com_light_object_id_maker.nextval"
			tableName:@"commercial_light"
			whereClause:@"object_id = 1"];
		id currentAccount = [rootController currentObject];

		[object setObjectID:nextKeyVal];
		[object setParent:currentAccount];
		[object setTI_ACCOUNT_NO:[currentAccount TI_ACCOUNT_NO]];
	}

	else if (controller == institutionalEOController) {
		int nextKeyVal = [uniqController uniqueIDForKey:@"institutional_object_id_maker.nextval"
			tableName:@"institutional"
			whereClause:@"object_id = 1"];
		id currentAccount = [rootController currentObject];

		[object setObjectID:nextKeyVal];
		[object setParent:currentAccount];
		[object setTI_ACCOUNT_NO:[currentAccount TI_ACCOUNT_NO]];
	}

	else if (controller == industrialEOController) {
		int nextKeyVal = [uniqController uniqueIDForKey:@"industrial_object_id_maker.nextval"
			tableName:@"industrial"
			whereClause:@"object_id = 1"];
		id currentAccount = [rootController currentObject];

		[object setObjectID:nextKeyVal];
		[object setParent:currentAccount];
		[object setTI_ACCOUNT_NO:[currentAccount TI_ACCOUNT_NO]];
	}

	else if (controller == highBillEOController) {
		int nextKeyVal = [uniqController uniqueIDForKey:@"high_bill_object_id_maker.nextval"
			tableName:@"high_bill"
			whereClause:@"object_id = 1"];
		id currentAccount = [rootController currentObject];

		[object setObjectID:nextKeyVal];
		[object setParent:currentAccount];
		[object setTI_ACCOUNT_NO:[currentAccount TI_ACCOUNT_NO]];
	}

	else if (controller == motorEOController) {
		int nextKeyVal = [uniqController uniqueIDForKey:@"motor_object_id_maker.nextval"
			tableName:@"motor"
			whereClause:@"object_id = 1"];
		id currentAccount = [rootController currentObject];

		[object setObjectID:nextKeyVal];
		[object setParent:currentAccount];
		[object setTI_ACCOUNT_NO:[currentAccount TI_ACCOUNT_NO]];
	}



	return YES;
}

- (BOOL)associationWillEdit:anAssociation
{	
	/*  Here we format the entered date string, and set the NSDictionary value upon successful date parsing.  If unsuccessful, we throw an alert panel, and recommend a standard date format to try.  Note that the dateWithCalendarFormat: method below takes in a string @"%b %d, %Y", which is the same as you will find in the CIS.eomodel for the INSTALLED_DATE and REBATE_FORM_DATE.  Eventually, we can make the date format a part of user preferences, but for now, pick an acceptable format, and use it in the code below, as well as in the eomodel for each date attribute.  Once this is done for dates in the eomodel, simply add the new date attributes in the line directly below (by or'ing each key comparison as I have done with REBATE_FORM_DATE, and that key will be validated on entry.
	*/

	if ([dateKeys containsObject:[anAssociation key]]) {

		id theDate = [NSCalendarDate dateFromRawString:[anAssociation value]];
		id theObject = [[anAssociation controller] currentObject];
		if (!theDate) {
			NXRunAlertPanel("Invalid Date Format","Use Format mm-dd-yy",NULL,NULL,NULL);
			return NO;
		}
		else {
			id newDictionary = [NSMutableDictionary dictionary];
			[(NSMutableDictionary *) newDictionary setObject:[theDate dateWithCalendarFormat:@"%b %d, %Y" timeZone:[NSTimeZone timeZoneWithName:@"PST"]] forKey:[anAssociation key]];
			[theObject takeValuesFromDictionary:newDictionary];
		}
	}

	return YES;
}

- (void)controller:(EOController *)controller didFetchObjects:(NSArray *)objects
{
	if (controller == waterHeaterEOController) {
		id currentAccount = [rootController currentObject];

/*		NSEnumerator * enum = [objects objectEnumerator];
		id theWaterHeater = nil;
	
		while (theWaterHeater = [enum nextObject])
			[theWaterHeater setParent:currentAccount];
*/
		
		[objects makeObjectsPerform:@selector(setParent:) withObject:currentAccount];
	}

	else if (controller == weatherizationEOController) {
		id currentAccount = [rootController currentObject];		
		[objects makeObjectsPerform:@selector(setParent:) withObject:currentAccount];
	}


	else if (controller == superGoodCentsEOController) {
		id currentAccount = [rootController currentObject];		
		[objects makeObjectsPerform:@selector(setParent:) withObject:currentAccount];
	}

	else if (controller == heatPumpEOController) 
		[objects makeObjectsPerform:@selector(setParent:) withObject:[rootController currentObject]];

	else if (controller == commercialLightEOController) {
		id currentAccount = [rootController currentObject];
		[objects makeObjectsPerform:@selector(setParent:) withObject:currentAccount];
	}

	else if (controller == institutionalEOController) 
		[objects makeObjectsPerform:@selector(setParent:) withObject:[rootController currentObject]];

	else if (controller == industrialEOController) 
		[objects makeObjectsPerform:@selector(setParent:) withObject:[rootController currentObject]];

	else if (controller == motorEOController) 
		[objects makeObjectsPerform:@selector(setParent:) withObject:[rootController currentObject]];

	else if (controller == highBillEOController) 
		[objects makeObjectsPerform:@selector(setParent:) withObject:[rootController currentObject]];

	[super controller:controller didFetchObjects:objects];
	

}

/*
- (void)controllerDidChangeSelection:(EOController *)aController
{
	// This method needs to update the vendor # field of the UI for the selected invoice

	if (aController == waterHeaterEOController) {
	
		if ([[aController selectedObjects] count] == 1)	
			[dwellingCategoryField setStringValue:[[[aController currentObject] DWELLING_CATEGORY] cString]];
		else
			[dwellingCategoryField setStringValue:""];
	}

	[super controllerDidChangeSelection:aController];
}
*/



- (void)queryController:(TDQueryController *)aQueryController 
	didSetValuesInObject:(id)rootObject
	usingObject:(id)pickedObject;
{
 
//	NSString *temp = [[NSString alloc] initWithCString:"CATEGORY_NAME"];
	NSString *temp1 = @"CATEGORY_NAME";
	NSString *temp2 = nil;

//	int a, b, c  = 0;
//	c = (a + b);


/* set the waterheater value according to the selected category  rootObject waterHeater pickedObject is EOGeneric */

	temp2 = [pickedObject objectForKey:temp1];

//	temp2 = [pickedObject objectForKey:@"CATEGORY_NAME"];
//	[temp release];

//  instance of a waterheater is the -, method setDWELLING_CATEGORY, to NSString = temp2: returns void
	[rootObject setDWELLING_CATEGORY:temp2];

}


- newWPDocument:sender
{
		/* Copy a template.wp document to the selected account's directory and open the copied file as Untitled. */
	[[Application workspace] openFile:"//SharedApps/.dsm/customerRequest/Untitled 1.wp"
    withApplication:"WordPerfect"];
	
	return self;
}

- openWPDocument:sender
{
		/* Bring up an OpenPanel, set to begin in directory startDir, initially trying to select file startFile, and filtering for file types contained in fileTypes. */

	const char *startDir = "/SharedApps/.dsm/customerRequest";
	const char *startFile = "";
	const char *fileTypes[2] = {"wp",NULL};

	OpenPanel *thePanel = [OpenPanel new];
	
	[thePanel allowMultipleFiles:NO];

	if ([thePanel runModalForDirectory:startDir file:startFile types:fileTypes] == NX_OKTAG)
			[[Application workspace] openFile:[thePanel filename]
   			withApplication:"WordPerfect"];
	
	return self;
}


- newMesaSpreadSheet:sender
{
		/* Copy a template.Mesa document to the selected account's directory and open the copied file as Untitled. */
	[[Application workspace] openFile:"/SharedApps/.dsm/customerRequest/template.Mesa"
    withApplication:"Mesa"];
	
	return self;
}

- openMesaSpreadSheet:sender
{
		/* Bring up an OpenPanel, set to begin in directory startDir, initially trying to select file startFile, and filtering for file types contained in fileTypes. */

	const char *startDir = "/SharedApps/.dsm/customerRequest";
	const char *startFile = "";
	const char *fileTypes[2] = {"Mesa",NULL};

	OpenPanel *thePanel = [OpenPanel new];
	
	[thePanel allowMultipleFiles:NO];

	if ([thePanel runModalForDirectory:startDir file:startFile types:fileTypes] == NX_OKTAG)
			[[Application workspace] openFile:[thePanel filename]
   			withApplication:"Mesa"];
	
	return self;
}


@end
