//
//  GCRadioGroupView.m
//
//  Created by Graham Cox on 8/04/2016.
//

#import "GCRadioGroupView.h"

@interface GCRadioGroupView ()
{
	NSInteger			mSelectedIndex;
	NSMutableArray*		mRadioButtons;
	BOOL				mEnabled;
}

@property (nonatomic, readonly) NSArray*	radioButtons;

- (IBAction)	_gc_radioButtonAction:(id) sender;

@end




@implementation GCRadioGroupView

@synthesize selectedIndex = mSelectedIndex;
@synthesize radioButtons = mRadioButtons;
@synthesize enabled = mEnabled;


- (void)		setSelectedIndex:(NSInteger) selectedIndex
{
	if( selectedIndex != mSelectedIndex )
	{
		mSelectedIndex = selectedIndex;
		NSInteger	k = 0;
		
		// this duplicates work done by NSView in 10.8+, but it's harmless to do it twice
		// and will work back to 10.6
		
		for( NSButton* rb in self.radioButtons )
		{
			rb.state = (k == selectedIndex)? NSOnState : NSOffState;
			++k;
		}
		
		NSLog(@"selected index = %ld", selectedIndex );
	}
}


- (void)		setEnabled:(BOOL) enabled
{
	mEnabled = enabled;
	
	for( NSButton* rb in self.radioButtons )
		rb.enabled = enabled;
}



- (IBAction)	_gc_radioButtonAction:(id) sender
{
	self.selectedIndex = [self.radioButtons indexOfObject:sender];
}


- (void)		awakeFromNib
{
	NSButton* lastOnButton = nil;
	
	// scan for buttons in the subviews
	
	for( NSView* sv in self.subviews )
	{
		if([sv isKindOfClass:[NSButton class]])
		{
			NSButton* button = (NSButton*)sv;
			
			// determining whether a button is a radio button is annoyingly awkward, because there's no -buttonType property.
			// we need to infer its type based on various properties, but it's really unclear what they uniquely are for radios.
			// for now, we'll just assume ALL subviews here are sensible radio buttons.
			
			//NSLog(@"button %@ bezel=%ld", sv, [(NSButton*)sv bezelStyle]);
			
			//if([(NSButton*)sv bezelStyle] == NSCircularBezelStyle )
			{
				// add to our list and make its action and target point here
				
				[mRadioButtons addObject:button];
				[button setAction:@selector(_gc_radioButtonAction:)];
				[button setTarget:self];
				
				// set the index to the last button we see that's ON
				
				if(button.state == NSOnState)
					lastOnButton = button;
			}
		}
	}
	
	// sort the button array in the most useful way for indexing. We can leave 'as is', use the tag, vertical position, etc.
	
	[mRadioButtons sortUsingComparator:^NSComparisonResult(NSButton* obj1, NSButton* obj2)
	{
		NSPoint a, b;
		
		a = [obj1 frame].origin;
		b = [obj2 frame].origin;
		
		return (a.y > b.y)? NSOrderedAscending : (a.y < b.y)? NSOrderedDescending : NSOrderedSame;
	}];
	
	if( lastOnButton )
		self.selectedIndex = [mRadioButtons indexOfObject:lastOnButton];
}


- (instancetype) initWithFrame:(NSRect) frameRect
{
	self = [super initWithFrame:frameRect];
	if( self )
	{
		mRadioButtons = [[NSMutableArray alloc] init];
		mSelectedIndex = -1;
	}
	
	return self;
}


/*
 
 // for non-ARC use
 

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

*/

@end
