/*------------------------------------------------------------------------------
 src/lib/djWidget/imageOpCropWidget.cxx
 
 Copyright (c) 2004-2006 Darby Johnston.
 All rights reserved.
 Use is subject to license terms.
------------------------------------------------------------------------------*/

//#define DJ_DBG
#include "djImageOpCoreWidget.h"
#include <djLabelWidget.h>
#include <djVecWidget.h>

namespace dj {

ImageOpCropWidget::ImageOpCropWidget() :
  _callbacks(true)
{
  LabelWidget * positionLabel = new LabelWidget("Position:");
  _positionWidget = new Vec2iWidget;
  LabelWidget * sizeLabel = new LabelWidget("Size:");
  _sizeWidget = new Vec2iWidget;
  
  List<LabelWidget *> labelList;
  labelList += positionLabel;
  labelList += sizeLabel;
  positionLabel->labelGroup(labelList);
  sizeLabel->labelGroup(labelList);
  
  VLayout * layout = new VLayout(this);
  HLayout * subLayout = new HLayout(layout);
  subLayout->margin(0);
  subLayout->add(positionLabel);
  subLayout->add(_positionWidget);
  subLayout = new HLayout(layout);
  subLayout->margin(0);
  subLayout->add(sizeLabel);
  subLayout->add(_sizeWidget);
  layout->stretchAdd();
  
  widgetUpdate();
  
  _positionWidget->sig().set(this, positionCallback);
  _sizeWidget->sig().set(this, sizeCallback);
}

void ImageOpCropWidget::set(ImageOp * in)
{
  ImageOpWidget::set(in);
  widgetUpdate();
}

void ImageOpCropWidget::widgetUpdate()
{
  _callbacks = false;
  
  Box2i area;
  if (_op) {
    StrList data = _op->attr(imageOpCropAttrStr()[ImageOpCrop::ATTR_AREA]);
    inflateStr(data, &area);
  }
  _positionWidget->set(area.position());
  _sizeWidget->set(area.size());
  
  _callbacks = true;
}

void ImageOpCropWidget::sizeCallback(const Vec2i & in)
{
  if (! _callbacks || ! _op) return;
  _op->attr(
    imageOpCropAttrStr()[ImageOpCrop::ATTR_AREA],
    deflateStr(Box2i(_positionWidget->get(), in))
  );
  sig().emit(true);
  widgetUpdate();
}

void ImageOpCropWidget::positionCallback(const Vec2i & in)
{
  if (! _callbacks || ! _op) return;
  _op->attr(
    imageOpCropAttrStr()[ImageOpCrop::ATTR_AREA],
    deflateStr(Box2i(in, _sizeWidget->get()))
  );
  sig().emit(true);
  widgetUpdate();
}

}
