#include "stdafx.h"

#include "mdc_layouter.h"
#include "mdc_figure.h"
#include "mdc_draw_util.h"

using namespace mdc;

Layouter::Layouter(Layer *layer)
  : CanvasItem(layer)
{
  _corner_mask= CNone;
  _corner_radius= 0.0;
  _draw_background= false;
}


Layouter::~Layouter()
{
}


void Layouter::render(CairoCtx *cr)
{
  draw_state(cr);

  if (_draw_background)
  {
    stroke_outline(cr);
    cr->set_line_width(1.0);
    cr->set_color(_background_color);
    cr->fill_preserve();
    cr->set_color(_border_color);
    cr->stroke();
  }
}


void Layouter::stroke_outline(CairoCtx *cr, float offset)
{
  stroke_rounded_rectangle(cr, get_bounds(), _corner_mask, _corner_radius, offset);
}


void Layouter::render_gl(CairoCtx *cr)
{  
  cr->save();
  draw_state(cr);
  cr->restore();

  if (_draw_background)
  {    
    gl_setcolor(_background_color);
    gl_rectangle(GL_QUADS, get_bounds());
    gl_setcolor(_border_color);
    gl_rectangle(GL_LINE_LOOP, get_bounds());
  }
}


void Layouter::remove_all()
{
  foreach(sigc::mem_fun(this, &Layouter::remove));

  set_needs_relayout();
}


static void find_item(mdc::CanvasItem *item, const std::string &tag,
                      mdc::CanvasItem **found_item)
{
  if (*found_item)
    return;

  if (item->get_tag() == tag)
  {
    *found_item= item;
    return;
  }

  Layouter *sub= dynamic_cast<Layouter*>(item);
  if (sub)
    *found_item= sub->find_item_with_tag(tag);
}


CanvasItem *Layouter::find_item_with_tag(const std::string &tag)
{
  CanvasItem *ret= 0;
  
  foreach(sigc::bind<std::string,mdc::CanvasItem**>(sigc::ptr_fun(find_item), tag, &ret));

  return ret;
}


void Layouter::set_draw_background(bool flag)
{
  _draw_background= flag;
  set_needs_render();
}


void Layouter::set_background_corners(mdc::CornerMask mask, float radius)
{
  _corner_mask= mask;
  _corner_radius= radius;
}


void Layouter::set_background_color(const mdc::Color &color)
{
  _background_color= color;
  set_needs_render();
}


void Layouter::set_border_color(const mdc::Color &color)
{
  _border_color= color;
  set_needs_render();
}


