#import "ModBusClass.h"

@implementation ModBusClass

-(void) dealloc
{
	[super dealloc];
}

-(NSMutableArray *) parameters
{
	return parameters;
}

-(void) loadParameters
{
	if(parameters) 
	{
		[parameters release];
        parameters = nil;
    }

	int i;
	parameters = [[NSMutableArray alloc] init];
	parametersValue = [[NSMutableArray alloc] initWithCapacity: INITIAL_PARAMETERS_COUNT];
	for (i=0;i<INITIAL_PARAMETERS_COUNT;i++) 
	{
		[parameters addObject:[[Parameter alloc] init]];
		[parametersValue addObject:[[NSNumber numberWithInt: -1] init]];
	}
	
}

- (void)awakeFromNib
{
	NSString* nom;

	[self loadParameters];
	nom = [[parameters objectAtIndex:0] name];

//	NSLog(@"Parameter %@", nom);

    [coilValues setDataSource:self];
    [coilValues setDelegate:self];

    [coilValues sizeLastColumnToFit];
	
    [registerValues setDataSource:self];
    [registerValues setDelegate:self];

    [registerValues sizeLastColumnToFit];
}

- (void)Initialize: (int)sizeArray
{
	[self awakeFromNib]; // Basic Initializiation
    [coilValues setNeedsDisplay:YES];
    [registerValues setNeedsDisplay:YES];

	coilsRange.location = START_ADDRESS_COILS;
	coilsRange.length = NUMBER_OF_COILS;
	
	holdingRegistersRange.location = START_ADDRESS_REGISTERS;
	holdingRegistersRange.length = NUMBER_OF_REGISTERS;
}

- (int)numberOfRowsInTableView:(NSTableView *)tableView
{
	int number;
	
	switch ([tableView tag])
	{
		case 0:
			number = NUMBER_OF_COILS;
			break;
		case 1:
			number = NUMBER_OF_REGISTERS;
			break;
		default:
			number = 1;
			break;
	}
	
	return number;
}

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
{
	Parameter* parameter;
	switch([tableView tag])
	{
	case 0:
		parameter = [parameters objectAtIndex:row];
		break;
	case 1:
		int newRow = row + NUMBER_OF_COILS;
		parameter = [parameters objectAtIndex:newRow];
		break;
	}
	
	return [parameter valueForKey:[tableColumn identifier]];
}

- (void)tableView:(NSTableView *)tableView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn row:(int)row
{
	Parameter* parameter;

	switch([tableView tag])
	{
	case 0:
		parameter = [parameters objectAtIndex:row];
		break;
	case 1:
		int newRow = row + NUMBER_OF_COILS;
		parameter = [parameters objectAtIndex:newRow];
		break;
	}
	
	[parameter takeValue:object forKey:[tableColumn identifier]];
}

- (IBAction)Connect:(id)sender
{
	NSString* blabla;
	NSString* suffixe = @"connected";
	NSString* version = @"0.0";
	blabla = [serverName stringValue];
	NSLog(@"%@ is %@", blabla, suffixe);
	
	[mbKit initialize];
	version = [mbKit modbuskitVersion];
	NSLog(@"Version is %@", suffixe);
	[mbkVersion setStringValue:version];

	mbKit = [mbKit initWithTCP:blabla port:502];
	
	int status;
	status = [mbKit openConnection];
	if (status == 0)
		[serverStatus setStringValue:suffixe];
	else
		[serverStatus setIntValue:status];
		
	
	[self UpdateDatas];	
}

- (IBAction)Load:(id)sender
{
	NSLog(@"Load Data");

	int i;
	for (i=0;i<INITIAL_PARAMETERS_COUNT;i++) 
	{
		Parameter* parameter = [parameters objectAtIndex:i];
		NSString* nom = TabledeNom[i];
		int num = TabledAddresses[i];
		[parameter setName:nom];
		[parameter setAddress:num];
	}
	
    [coilValues reloadData];
    [registerValues reloadData];
}

- (IBAction)ReadCoils:(id)sender
{
	modbusValue = [mbKit readCoil:1 startAddress:START_ADDRESS_COILS coilCount:NUMBER_OF_COILS];

	int i;
	int size = [modbusValue count];
	NSString *n = [[NSNumber numberWithInt:(size)] stringValue];
	NSLog(@"Number of Coils read : %@", n);

	if (size < NUMBER_OF_COILS)
	{
		NSLog(@"Warning not enough data go to simulation mode");
		[modbusValue release];
		modbusValue = [[NSMutableArray alloc] initWithCapacity: NUMBER_OF_COILS];
		for (i = 0; i < NUMBER_OF_COILS;i++) 
		{
			int val = i;
			[modbusValue addObject:[NSNumber numberWithInt: val]];
		}
	}

	for (i = 0; i < NUMBER_OF_COILS; i++)
	{
		[parametersValue replaceObjectAtIndex:i withObject:[modbusValue objectAtIndex:i]];
	}

    [self UpdateDatas];
}

- (IBAction)WriteCoils:(id)sender
{
	int i;
	transferData = [[NSMutableArray alloc] init];
	for (i = 0; i < NUMBER_OF_COILS;i++) 
	{
		Parameter* parameter = [parameters objectAtIndex:i];
		NSNumber* num = [parameter value];
		NSString *n = [num stringValue];
		NSLog(@"Value : %@", n);
		[transferData addObject:[num init]];
	}
	
	[mbKit writeMultipleCoils:1 startAddress:START_ADDRESS_COILS coilCount:NUMBER_OF_COILS stateData:transferData];
	
    [coilValues reloadData];
	[transferData autorelease];
}


- (IBAction)ReadHoldingRegisters:(id)sender
{
 	modbusValue = [mbKit readHoldingRegisters:1 startAddress:START_ADDRESS_REGISTERS registerCount:NUMBER_OF_REGISTERS];
	int i;

	int size = [modbusValue count];
	NSString *n = [[NSNumber numberWithInt:(size)] stringValue];
	NSLog(@"Number of HoldingRegister read : %@", n);

	if (size < NUMBER_OF_REGISTERS)
	{
		NSLog(@"Warning not enough data go to simulation mode");
		[modbusValue release];
		modbusValue = [[NSMutableArray alloc] initWithCapacity: NUMBER_OF_REGISTERS];
		for (i = 0;i < NUMBER_OF_REGISTERS; i++) 
		{
			int val = 2 * i;
			[modbusValue addObject:[NSNumber numberWithInt: val]];
		}
	}
	
	for (i = 0; i < NUMBER_OF_REGISTERS; i++)
	{
		int index = i + NUMBER_OF_COILS;
		[parametersValue replaceObjectAtIndex:index withObject:[modbusValue objectAtIndex:i]];
	}

    [self UpdateDatas];
}

- (IBAction)WriteHoldingRegisters:(id)sender
{
	int i;

	transferData = [[NSMutableArray alloc] init];
	for (i = 0; i < NUMBER_OF_REGISTERS;i++) 
	{
		int index = i + NUMBER_OF_COILS;
		Parameter* parameter = [parameters objectAtIndex:index];
		NSNumber* num = [parameter value];
		NSString *n = [num stringValue];
		NSLog(@"Value : %@", n);
		[transferData addObject:[num init]];		
	}

	[mbKit writeMultipleHoldingRegisters:1 startAddress:START_ADDRESS_REGISTERS registerCount:NUMBER_OF_REGISTERS valueData:transferData];
	
    [registerValues reloadData];
	[transferData autorelease];
}

-(void) UpdateDatas
{
	NSLog(@"Update Datas");

	int i;
	for (i = 0; i<INITIAL_PARAMETERS_COUNT; i++) 
	{
		Parameter* parameter = [parameters objectAtIndex:i];
		NSNumber* data = [parametersValue objectAtIndex:i];
		[parameter setValue:[data intValue]];
	}
	
    [coilValues reloadData];
    [registerValues reloadData];
}

- (void)tableViewSelectionDidChange:(NSNotification *)notification
{
    // Parameter *parameter = [parameters objectAtIndex:[coilValues selectedRow]];
}

@end
