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

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

#import "MFLabel.h"

enum
{
  ExpandFlag = (1<<0),
  FillFlag =   (1<<1),
  PackEndFlag= (1<<2),
  RemovingFlag=(1<<3), // the subview is being removed and should be ignored
  
  BoxFlagMask= 0xf
};

@implementation MFBoxImpl

- (id)initWithObject:(::mforms::Box*)aBox
{
  self= [super initWithFrame:NSMakeRect(10,10,10,10)];
  if (self)
  {
    mOwner= aBox;
    mOwner->set_data(self);
  }
  return self;
}


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


- (BOOL)isFlipped
{
  return YES;
}


- (void)setHorizontal:(BOOL)flag
{
  mHorizontal= flag;
}


- (void)setHomogeneous:(BOOL)flag
{
  mHomogeneous= flag;
}


- (void)setSpacing:(int)spacing
{
  mSpacing= spacing;
}


- (void)resizeSubviewsWithOldSizeH:(NSSize)oldBoundsSize
{
  NSSize minSize= [self preferredSize];
  NSSize size= [self frame].size;
  NSRect subframe;
  float leftover;
  int expandingSubviews= 0;
  int visibleSubviews= 0;
  BOOL packingEnd= NO;

  for (id subview in [self subviews])
  {
    if (![subview isHidden])
    {
      visibleSubviews++;
      if ([subview tag] & ExpandFlag)
        expandingSubviews++;
    }
  }
    
  subframe.origin.x= mPadding;
  subframe.origin.y= mPadding;
  subframe.size.height= size.height - 2 * mPadding;

  if (!mHomogeneous)
  {
    // calc space that's left to be distributed among all subviews
    leftover= (size.width - minSize.width);    
  }
  else
    leftover= 0;

  // compensate for the unneeded spacing added for the 1st item
  subframe.origin.x-= mSpacing;
  for (id subview in [self subviews])
  {
    if ([subview isHidden]) continue;
    
    NSSize minSubsize;
    BOOL expand= [subview tag] & ExpandFlag;
    BOOL fill= [subview tag] & FillFlag;
    float extraSpace= 0;
    
    minSubsize= [subview preferredSize];
   
    if (!packingEnd && ([subview tag] & PackEndFlag))
    {
      packingEnd= YES;
      if (expandingSubviews == 0)
        subframe.origin.x+= leftover;
    }
    
    subframe.origin.x+= mSpacing;
    
    if (mHomogeneous)
    {
      float spacePerCell= (size.width - (2 * mPadding + (visibleSubviews-1) * mSpacing)) / visibleSubviews;
      
      if (fill)
        subframe.size.width= spacePerCell;
      else
      {
        subframe.size.width= minSubsize.width;
        subframe.origin.x+= (spacePerCell - minSubsize.width) / 2;
        extraSpace= (spacePerCell - minSubsize.width) / 2;
      }
    }
    else
    {
      subframe.size.width= minSubsize.width;
      if (expand)
      {
        extraSpace= leftover / expandingSubviews;
        if (fill)
          subframe.size.width+= extraSpace; // use all the space given to us
        else
          subframe.origin.x+= extraSpace / 2; // just center in the space given to us
      }
    }
    subframe.origin.x= round(subframe.origin.x);
    subframe.size.width= round(subframe.size.width);

    if (NSEqualRects([subview frame], subframe))
      [subview resizeSubviewsWithOldSize: subframe.size];
    else      
    {
      NSRect f= subframe;
      
      if ([subview respondsToSelector:@selector(heightIsFixed)] &&
          [subview heightIsFixed])
      {
        f.size.height= minSubsize.height;
        f.origin.y= f.origin.y + floor((NSHeight(subframe) - NSHeight(f))/2);
      }
      [subview setFrame: f];
    }
    
    subframe.origin.x+= NSWidth(subframe);
    if (expand && !fill)
      subframe.origin.x+ extraSpace;
  }
}



- (void)resizeSubviewsWithOldSizeV:(NSSize)oldBoundsSize
{
  NSSize minSize= [self preferredSize];
  NSSize size= [self frame].size;
  NSRect subframe;
  float leftover;
  int expandingSubviews= 0;
  int visibleSubviews= 0;
  BOOL packingEnd= NO;
  
  for (id subview in [self subviews])
  {
    if (![subview isHidden])
    {
      visibleSubviews++;
      if ([subview tag] & ExpandFlag)
        expandingSubviews++;
    }
  }
  
  subframe.origin.x= mPadding;
  subframe.origin.y= mPadding;
  subframe.size.width= size.width - 2 * mPadding;
  
  if (!mHomogeneous)
  {
    // calc space that's left to be distributed among all subviews
    leftover= (size.height - minSize.height);
  }
  else
    leftover= 0;
  
  // compensate for the unneeded spacing added for the 1st item
  subframe.origin.y-= mSpacing;
  for (id subview in [self subviews])
  {
    if ([subview isHidden]) continue;
    
    NSSize minSubsize;
    BOOL expand= [subview tag] & ExpandFlag;
    BOOL fill= [subview tag] & FillFlag;
    float extraSpace= 0;

    if ([subview isKindOfClass: [MFLabelImpl class]])
      minSubsize= [subview preferredSizeForWidth: size.width];
    else
      minSubsize= [subview preferredSize];
    
    if (!packingEnd && ([subview tag] & PackEndFlag))
    {
      packingEnd= YES;
      if (expandingSubviews == 0)
        subframe.origin.y+= leftover;
    }
    
    subframe.origin.y+= mSpacing;
    
    if (mHomogeneous)
    {
      float spacePerCell= (size.height - (2 * mPadding + (visibleSubviews-1) * mSpacing)) / visibleSubviews;
      
      if (fill)
        subframe.size.height= spacePerCell;
      else
      {
        subframe.size.height= minSubsize.height;
        subframe.origin.y+= (spacePerCell - minSubsize.height) / 2;
        extraSpace= (spacePerCell - minSubsize.height) / 2;
      }
    }
    else
    {
      subframe.size.height= minSubsize.height;
      if (expand)
      {
        extraSpace= leftover / expandingSubviews;
        if (fill)
          subframe.size.height+= extraSpace; // use all the space given to us
        else
          subframe.origin.y+= extraSpace / 2; // just center in the space given to us
      }
    }

    subframe.origin.y= round(subframe.origin.y);
    subframe.size.height= round(subframe.size.height);
    if (NSEqualRects([subview frame], subframe))
      [subview resizeSubviewsWithOldSize: subframe.size];
    else
      [subview setFrame:subframe];
    
    subframe.origin.y+= NSHeight(subframe);
    if ((mHomogeneous || expand) && !fill)
      subframe.origin.y+= extraSpace;
  }
}



- (void)resizeSubviewsWithOldSize:(NSSize)oldBoundsSize
{
  if (mHorizontal)
    [self resizeSubviewsWithOldSizeH:oldBoundsSize];
  else
    [self resizeSubviewsWithOldSizeV:oldBoundsSize];
}


- (NSSize)minimumSize
{
  NSSize size;
  float maxSize= 0;
  float frameWidth= NSWidth([self frame]);
  int visibleSubviews= 0;
  
  size.width= 0;
  size.height= 0;
  
  for (id subview in [self subviews])
  {
    NSSize minSize;
    if (![subview isHidden])
    {
      visibleSubviews++;
      
      if ([subview isKindOfClass: [MFLabelImpl class]])
        minSize= [subview preferredSizeForWidth: frameWidth];
      else        
        minSize= [subview preferredSize];
      
      if (mHorizontal)
      {
        size.width+= minSize.width;
        maxSize= MAX(maxSize, minSize.width);
        size.height= MAX(size.height, minSize.height);
      }
      else
      {
        size.width= MAX(size.width, minSize.width);
        maxSize= MAX(maxSize, minSize.height);
        size.height+= minSize.height;
      }
    }
  }
  
  if (mHomogeneous)
  {
    if (mHorizontal)
      size.width= maxSize * visibleSubviews;
    else
      size.height= maxSize * visibleSubviews;
  }
  
  size.width+= mPadding * 2;
  size.height+= mPadding * 2;
  if (mHorizontal)
    size.width+= (visibleSubviews-1) * mSpacing;
  else
    size.height+= (visibleSubviews-1) * mSpacing;
  
  return size;
}


- (void)didAddSubview:(NSView *)subview
{
  [self subviewMinimumSizeChanged];
}


- (void)willRemoveSubview:(NSView *)subview
{
  // mark the subview so that it's not accounted when relayouting
  [(id)subview setTag: ([subview tag]&~BoxFlagMask) | RemovingFlag];
  
  [self subviewMinimumSizeChanged];
}


#if 0
- (void)drawRect:(NSRect)rect
{
  [[NSColor redColor] set];
  NSFrameRect([self frame]);
  /*
  [[NSColor blueColor] set];
  NSFrameRect(NSInsetRect([self frame], 1, 1));
  */
  [[NSColor orangeColor] set];
  NSFrameRect(NSInsetRect([self frame], 5, 5));
  
  [[NSColor purpleColor] set];
  for (id view in [self subviews])
  {
    NSFrameRect([view frame]);
  }
}
#endif

static bool box_create(::mforms::Box *self, bool horiz)
{
  MFBoxImpl *box= [[[MFBoxImpl alloc] initWithObject:self] autorelease];
  
  [box setHorizontal:horiz ? YES : NO];
  
  return true;  
}


static void box_set_padding(::mforms::Box *self, int padding)
{
  if ( self )
  {
    MFBoxImpl* box = self->get_data();
    
    if ( box )
    {
      [box setPadding:padding];
    }
  }
}


static void box_set_spacing(::mforms::Box *self, int spacing)
{
  if ( self )
  {
    MFBoxImpl* box = self->get_data();
    
    if ( box )
    {
      [box setSpacing:spacing];
    }
  }
}


static void box_set_homogeneous(::mforms::Box *self, bool flag)
{
  if ( self )
  {
    MFBoxImpl* box = self->get_data();
    
    if ( box )
    {
      [box setHomogeneous:flag];
    }
  }
}



static void box_add(::mforms::Box *self, ::mforms::View *child, bool expand, bool fill)
{
  if ([child->get_data() tag] < 0)
    NSLog(@"NEGATIVE TAG IN NEW OBJECT %i", [child->get_data() tag]);

  NSUInteger flags= [child->get_data() tag] & ~BoxFlagMask;
  id last= nil;
  if (expand)
    flags|= ExpandFlag;
  if (fill)
    flags|= FillFlag;
  
  // use the tag of the view to store layout flags
  [child->get_data() setTag:flags];
  
  // find the 1st subview that's packed to the end
  for (id sub in [self->get_data() subviews])
  {
    if ([sub tag] & PackEndFlag)
    {
      last= sub;
      break;
    }
  }

  // there's nothing packed to the end, so just add to the end
  if (!last)
    [self->get_data() addSubview:child->get_data()];
  else // if there's something packed to end, add it before (ie below) it
    [self->get_data() addSubview:child->get_data() positioned:NSWindowBelow relativeTo:last];
  assert([child->get_data() superview] == self->get_data());
  [self->get_data() subviewMinimumSizeChanged];
}


static void box_add_end(::mforms::Box *self, ::mforms::View *child, bool expand, bool fill)
{
  if ([child->get_data() tag] < 0)
    NSLog(@"NEGATIVE TAG IN NEW OBJECT %i", [child->get_data() tag]);

  NSUInteger flags= ([child->get_data() tag] & ~BoxFlagMask) | PackEndFlag;
  id last= nil;
  if (expand)
    flags|= ExpandFlag;
  if (fill)
    flags|= FillFlag;
  
  // use the tag of the view to store layout flags
  [child->get_data() setTag:flags];
  
  // find the 1st subview that's packed to the end
  for (id sub in [self->get_data() subviews])
  {
    if ([sub tag] & PackEndFlag)
    {    
      last= sub;
      break;
    }
  }

  if (!last)
    [self->get_data() addSubview:child->get_data() positioned:NSWindowAbove relativeTo:nil];
  else
    [self->get_data() addSubview:child->get_data() positioned:NSWindowBelow relativeTo:last];
  assert([child->get_data() superview] == self->get_data());
  [self->get_data() subviewMinimumSizeChanged];
}


static void box_remove(::mforms::Box *self, ::mforms::View *child)
{
  [child->get_data() removeFromSuperview];
}


void cf_box_init()
{
  ::mforms::ControlFactory *f = ::mforms::ControlFactory::get_instance();
  
  f->_box_impl.create= &box_create;
  f->_box_impl.set_padding= &box_set_padding;
  f->_box_impl.set_spacing= &box_set_spacing;
  f->_box_impl.add= &box_add;
  f->_box_impl.add_end= &box_add_end;
  f->_box_impl.remove= &box_remove;
  f->_box_impl.set_homogeneous= &box_set_homogeneous;
}

@end


