//
//  MFRadioButton.mm
//  MySQLWorkbench
//
//  Created by Alfredo Kojima on 7/Feb/09.
//  Copyright 2009 Sun Microsystems Inc. All rights reserved.
//

#import "MFRadioButton.h"

#import "MFView.h"
#include "mforms/mforms.h"

#import "MFPanel.h"

@implementation MFRadioButtonImpl


- (id)initWithObject:(::mforms::RadioButton*)aRadioButton
{
  self= [super initWithObject:aRadioButton];
  if (self)
  {
    [self setButtonType: NSRadioButton];
    [self setBezelStyle: NSRegularSquareBezelStyle];
    
    mTopLeftOffset= NSMakePoint(0, 0);
    mBottomRightOffset= NSMakePoint(0, 0);
    mAddPadding= NO;
    
    [self setTarget:self];
    [self setAction:@selector(performCallback:)];
  }
  return self;
}


- (void)performCallback:(id)sender
{
  if (sender == self)
  {
    // find the Panel where we're located and request it to unselect other radios
    id panel= [self superview];
    while (panel && ![panel isKindOfClass:[MFPanelImpl class]])
      panel= [panel superview];
    
    if (panel)
      [panel setSelectedRadio:self];
  }
  
  mOwner->callback();
  
  dynamic_cast<mforms::RadioButton*>(mOwner)->callback();
}


- (NSSize)minimumSize
{
  return [[self cell] cellSize];
}



static bool radiobutton_create(::mforms::RadioButton *self)
{
  [[[MFRadioButtonImpl alloc] initWithObject:self] autorelease];
  
  return true;  
}


static void radiobutton_set_text(::mforms::RadioButton *self, const std::string &text)
{
  if ( self )
  {
    MFRadioButtonImpl* radiobutton = self->get_data();
    
    if ( radiobutton )
    {
      [radiobutton setTitle: wrap_nsstring(text)];
      [radiobutton sizeToFit];
    }
  }
}

static void radiobutton_set_active(::mforms::RadioButton *self, bool flag)
{
  if ( self )
  {
    MFRadioButtonImpl* radiobutton = self->get_data();
    
    if ( radiobutton )
    {
      [radiobutton setState: flag ? NSOnState : NSOffState];
    }
  }
}

static bool radiobutton_get_active(::mforms::RadioButton *self)
{
  if ( self )
  {
    MFRadioButtonImpl* radiobutton = self->get_data();
    
    if ( radiobutton )
    {
      return [radiobutton state] == NSOnState;
    }
  }
  return false;
}


void cf_radiobutton_init()
{
  ::mforms::ControlFactory *f = ::mforms::ControlFactory::get_instance();
  
  f->_radio_impl.create= &radiobutton_create;
  f->_radio_impl.set_active= &radiobutton_set_active;
  f->_radio_impl.get_active= &radiobutton_get_active;
}


@end

