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

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

@implementation MFTextEntryImpl

- (id)initWithObject:(::mforms::TextEntry*)aEntry passwordEntry:(BOOL)flag
{
  self= [super initWithFrame: NSMakeRect(0, 0, 30, 0)];
  if (self)
  {
    if (flag)
    {
      NSSecureTextField *secureField= [[NSSecureTextField alloc] initWithFrame: NSMakeRect(0, 0, 30, 0)];
      [self setCell: [secureField cell]];
      [secureField release];
    } 
    mOwner= aEntry;
    mOwner->set_data(self);

    [self sizeToFit];
    mMinHeight= NSHeight([self frame]);
    
    [self setDelegate: self];
    
    [[self cell] setLineBreakMode: NSLineBreakByClipping];
    [[self cell] setScrollable: YES];
  }
  return self;
}

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


- (NSSize)minimumSize
{
  NSSize size= [[self cell] cellSize];
  
  size.height= mMinHeight;
  size.width= size.height;
  
  return size;
}


- (BOOL)heightIsFixed
{
  return YES;
}


- (void)setFrame:(NSRect)frame
{
  [super setFrame:frame];
}

/*
- (void)setFrame:(NSRect)frame
{
  float oheight= NSHeight(frame);
  if (oheight != mMinHeight)
  {
    NSLog(@"req %@", NSStringFromRect(frame));
    // limit the frame so that the height always stays at the minimum
    frame.size.height= mMinHeight;
    frame.origin.y-= round((oheight - mMinHeight) / 2);
    frame.origin.y= MAX(frame.origin.y, 0);
    NSLog(@"give %@", NSStringFromRect(frame));
  }
  [super setFrame:frame];
}*/


- (void)controlTextDidChange:(NSNotification *)aNotification
{
  mOwner->callback();
}


@end




static bool entry_create(::mforms::TextEntry *self, bool ispassword)
{
  MFTextEntryImpl *entry= [[[MFTextEntryImpl alloc] initWithObject:self passwordEntry:ispassword] autorelease];
    
  return entry != nil;
}


static void entry_set_text(::mforms::TextEntry *self, const std::string &text)
{
  if ( self )
  {
    MFTextEntryImpl* entry = self->get_data();
  
    [entry setStringValue:wrap_nsstring(text)];
  }
}


static void entry_set_max_length(::mforms::TextEntry *self, int maxlen)
{
  if ( self )
  {
//    MFTextEntryImpl* entry = self->get_data();
    
#warning missing code here
    //[entry set
  }
}


static std::string entry_get_text(::mforms::TextEntry *self)
{
  if ( self )
  {
    MFTextEntryImpl* entry = self->get_data();
    
    if (entry)
      return [[entry stringValue] UTF8String];
  }
  return "";
}



void cf_textentry_init()
{
  ::mforms::ControlFactory *f = ::mforms::ControlFactory::get_instance();
  
  f->_textentry_impl.create= &entry_create;
  f->_textentry_impl.set_text= &entry_set_text;
  f->_textentry_impl.get_text= &entry_get_text;
  f->_textentry_impl.set_max_length= &entry_set_max_length;
}



