//
//  cf_button.mm
//  MySQLWorkbench
//
//  Created by Alfredo Kojima on 21/Jan/09.
//  Copyright 2009 Sun Microsystems Inc. All rights reserved.
//

#import "MFButton.h"
#include <mforms/mforms.h>

@implementation MFButtonImpl

- (id)initWithObject:(::mforms::Button*)aButton
{
  self= [super initWithFrame:NSMakeRect(10, 10, 10, 10)];
  if (self)
  {
    [self setTag: 0];
    
    // buttons have some extra padding to the sides that we want to skip 
    mTopLeftOffset= NSMakePoint(6, 2);
    mBottomRightOffset= NSMakePoint(5, 5);
    
    mOwner= aButton;
    mOwner->set_data(self);
    
    [self setBezelStyle:NSRoundedBezelStyle];
    [self setTarget:self];
    [self setAction:@selector(performCallback:)];
  }
  return self;
}

- (NSString*)description
{
  return [NSString stringWithFormat:@"<%@ '%@'>", [self className], [self title]];
}

- (mforms::Object*)mformsObject
{
  return mOwner;
}


- (void)setFrame:(NSRect)frame
{
  if (![self widthIsFixed])
    frame.origin.x-= mTopLeftOffset.x;
  frame.origin.y-= mTopLeftOffset.y;
  
  // add back the extra padding for the button
  if (![self widthIsFixed])
    frame.size.width+= mTopLeftOffset.x + mBottomRightOffset.x;
  frame.size.height+= mTopLeftOffset.y + mBottomRightOffset.y;
  
  [super setFrame:frame];
}


- (void)performCallback:(id)sender
{
  mOwner->callback();
}

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


- (NSSize)minimumSize
{
  NSSize size= [[self cell] cellSize];
  
  // remove the extra padding given by the cell size
  size.width-= mTopLeftOffset.x + mBottomRightOffset.x;
  size.height-= mTopLeftOffset.y + mBottomRightOffset.y;
  
  // add some internal padding to the button to make it look nicer
  if (mAddPadding)
    size.width+= size.height;
  
  return size;
}


- (void)setTitle:(NSString*)title
{
  [super setTitle: title];

  [[self superview] subviewMinimumSizeChanged];
}



static bool button_create(::mforms::Button *self)
{
  [[[MFButtonImpl alloc] initWithObject:self] autorelease];
  
  return true;  
}


static void button_set_text(::mforms::Button *self, const std::string &text)
{
  if ( self )
  {
    MFButtonImpl* button = self->get_data();
    
    if ( button )
    {
      [button setTitle:[wrap_nsstring(text) stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"_"]]];
    }
  }
}


static void button_enable_internal_padding(::mforms::Button *self, bool pad)
{
  if ( self )
  {
    MFButtonImpl* button = self->get_data();
    
    if ( button )
    {
      button->mAddPadding= pad;
    }
  }
}


void cf_button_init()
{
  ::mforms::ControlFactory *f = ::mforms::ControlFactory::get_instance();
  
  f->_button_impl.create= &button_create;
  f->_button_impl.set_text= &button_set_text;
  f->_button_impl.enable_internal_padding= &button_enable_internal_padding;
}


@end


