#include "stdafx.h"


#include "mdc_figure.h"
#include "mdc_algorithms.h"
#include "mdc_canvas_view.h"

using namespace mdc;

Figure::Figure(Layer *layer) 
: CanvasItem(layer), _pen_color(Color::Black()), _fill_color(Color::White()), _line_width(1.0)
{
}


void Figure::render(CairoCtx *cr)
{
  draw_state(cr);
  draw_contents(cr);
}


void Figure::draw_contents_gl(CairoCtx *cr)
{
  throw std::logic_error("draw_contents_gl() not implemented for this figure");
}


void Figure::render_gl(CairoCtx *cr)
{
  draw_state(cr);
  draw_contents_gl(cr);
}


void Figure::stroke_outline(CairoCtx *cr, float offset)
{
  Rect bounds= get_bounds();
  
  cr->rectangle(bounds.xmin()-offset, bounds.ymin()-offset, bounds.width()+offset*2, bounds.height()+offset*2);
}


mdc::Point Figure::get_intersection_with_line_to(const Point &p)
{
  // this will return the intersection point of the line from the 
  // center of the object to the given point.
  Point center= get_root_position();
  Point p1;
  Point p2;

  center.x+= get_size().width/2;
  center.y+= get_size().height/2;

  // brute-force, subclasses should reimplement with their own version

  if (intersect_rect_to_line(get_bounds(), center, p, p1, p2))
  {
    cairo_surface_t *crs= cairo_image_surface_create(CAIRO_FORMAT_RGB24,
                                                     (int)get_size().width,
                                                     (int)get_size().height);
    {
      CairoCtx cr(crs);
      cr.rectangle(0, 0, get_size().width, get_size().height);
      cr.set_color(Color::Black());
      cr.fill();
  
      cr.translate(-get_position().x, -get_position().y);
      stroke_outline(&cr, 0);
      cr.set_color(Color::White());
      cr.fill();

      unsigned char *data= cairo_image_surface_get_data(crs);
      int stride= cairo_image_surface_get_stride(crs);
#define GET_PIXEL(x, y) data[((x+(y)*stride)*3)]
    
      //XXX
    }
    cairo_surface_destroy(crs);
  }
  return center;
}


void Figure::set_pen_color(const Color &color)
{
  _pen_color= color;
  set_needs_render();
}


void Figure::set_fill_color(const Color &color)
{
  _fill_color= color;
  set_needs_render();
}


void Figure::set_line_width(float width)
{
  _line_width= width;
  set_needs_render();
}

