#include <cstring>
#include "stdafx.h"
#include <string.h>

#include "mdc_canvas_view_image.h"
/**
 * @file  mdc_canvas_view_image.cpp
 * @brief 
 */

using namespace mdc;


ImageCanvasView::ImageCanvasView(int width, int height, cairo_format_t format)
  : CanvasView(width, height), _buffer(0), _format(format)
{
}


ImageCanvasView::~ImageCanvasView()
{
  if (_buffer)
    cairo_surface_destroy(_buffer);
}


void ImageCanvasView::begin_repaint(int x, int y, int w, int h)
{
}


void ImageCanvasView::end_repaint()
{
}


void ImageCanvasView::update_view_size(int width, int height)
{
  if (_buffer && _view_width == width && _view_height == height)
    return;

  if (_buffer)
    cairo_surface_destroy(_buffer);

  _buffer= cairo_image_surface_create(_format, width, height);

  delete _cairo;
  _cairo= new CairoCtx(_buffer);
  cairo_set_tolerance(_cairo->get_cr(), 0.1);

  update_offsets();
  set_needs_repaint();

  _viewport_changed_signal.emit();
}


void ImageCanvasView::save_to(const std::string &path)
{
  // clear in white
  memset(cairo_image_surface_get_data(_buffer), 0xff, 
         cairo_image_surface_get_stride(_buffer)*_view_height);

  render_for_export(Rect(Point(0,0), get_total_view_size()), 0);
  
  cairo_surface_write_to_png(_buffer, path.c_str());
}


const unsigned char* ImageCanvasView::get_image_data(size_t &size)
{
  repaint();

  size= cairo_image_surface_get_stride(_buffer)*_view_height;

  return cairo_image_surface_get_data(_buffer);
}
