//
//  PingThread.m
//  TagTool
//
//  Created by jcassidy on 10-10-29.
//  Copyright 2010 Visible Assets Inc.. All rights reserved.
//

#import "PingThread.h"
#import "Tag.h"
#import "TagDemoAppDelegate.h"
#import "DiscoveryViewController.h"

@implementation PingThread

// ***************************************************************
// *                                                             
// * init =  set initial state, record tag ID to be scanned
// *
// ***************************************************************

- init:(DiscoveryViewController *) d tagID:(long) t
{
	if( self = [super init] ) {
		isRunning = NO;
		shutdown = NO;
		discoveryViewController = d;
		tagID = t;
	}
	
	return self;
}

// ***************************************************************
// *                                                             
// * dealloc =  release any locally allocated objects
// *
// ***************************************************************

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

// ***************************************************************
// *                                                             
// * main =  thread execution starts here....
// *
// ***************************************************************

- (void) main
{
	Tag					*tag;
	BaseStation			*baseStation;
	NSAutoreleasePool	*autoreleasePool;
	
	// obligitory autorelease pool for this thread
	autoreleasePool = [[NSAutoreleasePool alloc] init];
	
	// get a reference to the basestation for transmission by tag
	baseStation = [(TagDemoAppDelegate *) [[UIApplication sharedApplication]  delegate] baseStation];
	if( ![baseStation isConnected] ) 
		return;
	
	// create a tag and initialize it for transmission
	tag = [[Tag alloc] init];
	[tag setBatchMode:TRUE];
	[tag setBaseStation:baseStation];	
	[tag setMaxRetransmissions:1];
	[tag setTagID:tagID];
	
	[tag wakeupTags];
	isRunning = YES;
	while( isRunning ) {
		if( [tag ping:tagID] ) {
			// got a valid ping - notify UI object
			[discoveryViewController tagPinged:tag];
		}
	}
	
	// cleanup local allocation
	[autoreleasePool release];
	
	shutdown = YES;
}

// ***************************************************************
// *                                                             
// * stop =  terminate this thread by ending it's control loop
// *
// ***************************************************************

- (void) stop
{
	isRunning = NO;
}

// ***************************************************************
// *                                                             
// * isShutdown =  returns true when thread's control loop has finished 
// *
// ***************************************************************

- (BOOL) isShutdown
{
	return shutdown;
}


@end
