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

#import "MFProgressBar.h"

#include "mforms/mforms.h"

@implementation MFProgressBarImpl


- (id)initWithObject:(::mforms::ProgressBar*)pbar
{
  self= [super initWithFrame:NSMakeRect(10,10,10,10)];
  if (self)
  {
    [self setMinValue: 0];
    [self setMaxValue: 1.0];
    [self setIndeterminate: NO];

    mOwner= pbar;
    mOwner->set_data(self);
  }
  return self;
}


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



- (NSSize)minimumSize
{
  return NSMakeSize(100, 20);
}


- (void)setTag:(NSInteger)tag
{
  mTag= tag;
}

- (NSInteger)tag
{
  return mTag;
}


static bool progressbar_create(mforms::ProgressBar *image)
{
  [[[MFProgressBarImpl alloc] initWithObject:image] autorelease];
  
  return true;
}


static void progressbar_set_value(mforms::ProgressBar *self, float pct)
{
  if (self)
  {
    static NSTimeInterval lastRedraw= 0.0;
    NSTimeInterval now;
    MFProgressBarImpl *impl= self->get_data();
    float lastValue= [impl doubleValue];
    [impl setDoubleValue: pct];

    // force a redraw with a time and pct based throttling
    now= [NSDate timeIntervalSinceReferenceDate];
    if (now - lastRedraw > 0.1 || pct - lastValue > 0.01f || pct == 0.0f || pct == 1.0f)
    {
      [[impl window] displayIfNeeded];
      lastRedraw= now;
    }
  }
}


static void progressbar_set_started(mforms::ProgressBar *self, bool flag)
{
  if (self)
  {
    MFProgressBarImpl *impl= self->get_data();
    if (flag)
      [impl startAnimation:nil];
    else
      [impl stopAnimation:nil];
  }
}


static void progressbar_set_indeterminate(mforms::ProgressBar *self, bool flag)
{
  if (self)
  {
    MFProgressBarImpl *impl= self->get_data();
    [impl setIndeterminate: flag];
  }
}

void cf_progressbar_init()
{
  ::mforms::ControlFactory *f = ::mforms::ControlFactory::get_instance();
  
  f->_progressbar_impl.create= &progressbar_create;
  f->_progressbar_impl.set_value= &progressbar_set_value;
  f->_progressbar_impl.set_started= &progressbar_set_started;
  f->_progressbar_impl.set_indeterminate= &progressbar_set_indeterminate;
}




@end
