/*
 *  mdc_icon_text.cpp
 *  mdcanvas
 *
 *  Created by Alfredo Kojima on 07/Mar/8.
 *  Copyright 2007 MySQL AB. All rights reserved.
 *
 */

#include "stdafx.h"

#include "mdc_canvas_view.h"
#include "mdc_layer.h"
#include "mdc_icon_text.h"

using namespace mdc;

IconTextFigure::IconTextFigure(Layer *layer)
: TextFigure(layer), _icon(0)
{
  _spacing= 5;
}


IconTextFigure::~IconTextFigure()
{
  if (_icon)
    cairo_surface_destroy(_icon);
}


mdc::Size IconTextFigure::calc_min_size()
{
  Size size= TextFigure::calc_min_size();
  
  if (_icon)
  {
    double w= cairo_image_surface_get_width(_icon);
    double h= cairo_image_surface_get_height(_icon);
    
    size.width= w + size.width + _spacing;
    size.height= std::max(size.height, h);
  }

  return size;
}


void IconTextFigure::auto_size()
{
  Size size;

  if (_text_layout)
  {
    _text_layout->relayout(get_layer()->get_view()->cairoctx());
    size= _text_layout->get_size();
    size.width += 2 * _xpadding;
    size.height += 2 * _ypadding;
  }
  else
  {
    cairo_text_extents_t extents;

    get_layer()->get_view()->cairoctx()->get_text_extents(_font, _text, extents);

    size.width= ceil(extents.x_advance);
    size.height= ceil(extents.height);
    
    size.width+= _xpadding*2;
    size.height+= _ypadding*2;
  }

  if (_icon)
    size.width+= cairo_image_surface_get_width(_icon) + _spacing;

  resize_to(size);
}


void IconTextFigure::draw_contents(CairoCtx *cr)
{
  Rect bounds= get_bounds();
  if (_icon)
  {
    int w= cairo_image_surface_get_width(_icon);
    int h= cairo_image_surface_get_height(_icon);
    int x;
    Point pos= get_position();
    
    pos.x+= _xpadding;
    pos.y+= _ypadding + (get_size().height-h-2*_ypadding)/2;
    
    x= w + (int)_spacing;
    cr->save();
    cr->translate(pos);
    cr->set_source_surface(_icon, 0, 0);
    cr->scale(1.0/w, 1.0/h);
    cr->paint();
    cr->restore();
  
    cr->translate(x, 0);

    bounds.size.width-= x;
  }
  TextFigure::draw_contents(cr, bounds);
}


void IconTextFigure::set_icon(cairo_surface_t *icon)
{
  if (icon != _icon)
  {
    if (_icon)
      cairo_surface_destroy(_icon);
    if (icon)
      _icon= cairo_surface_reference(icon);
    else
      _icon= NULL;
    set_needs_relayout();
  }
}


void IconTextFigure::set_spacing(double space)
{
  _spacing= space;
  set_needs_relayout();
}
