/* -*- Mode: Vala; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*- */
/*
    Multiplication Puzzle
    Copyright (C) 2004-2008,2011 Michael Terry <mike@mterry.name>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

using GLib;

/* Vala 0.12's bindings for this are wrong, so we make our own */
[CCode (cheader_filename = "gtk/gtk.h")]
extern void gtk_style_context_get_color(Gtk.StyleContext context,
                                 Gtk.StateFlags state,
                                 out Gdk.RGBA color);

public class CharBox : Gtk.EventBox
{
  public string letter { get; set; default = "?"; }
  public Gtk.ShadowType border { get; set; default = Gtk.ShadowType.NONE; }
  public int points { get; set; }
  
  private Gtk.StateFlags _highlight = Gtk.StateFlags.NORMAL;
  public Gtk.StateFlags highlight {
    get {return _highlight;}
    set {
      _highlight = value;
      queue_draw ();
    }
  }
  
  /* Private methods & members */
  private Gtk.DrawingArea area;
  
  private bool draw_request (Cairo.Context ctx)
  {
    var w = area.get_allocated_width();
    var h = area.get_allocated_height();
    var style = get_style_context ();

    style.save();
    style.add_class(Gtk.STYLE_CLASS_RUBBERBAND);
    style.set_state(highlight);

    if (highlight != Gtk.StateFlags.NORMAL)
      Gtk.render_background (style, ctx, 0, 0, w, h);

    if (border != Gtk.ShadowType.NONE)
      Gtk.render_frame (style, ctx, 0, 0, w, h); // FIXME: highlight/border?
    
    // Letter
    Gdk.RGBA color;
    gtk_style_context_get_color(style, highlight, out color);
    ctx.set_source_rgba(color.red, color.green, color.blue, color.alpha);

    ctx.set_font_size (points);
    
    Cairo.TextExtents te = Cairo.TextExtents();
    ctx.text_extents (_(letter), out te);
    
    Cairo.FontExtents fe = Cairo.FontExtents();
    ctx.font_extents (out fe);
    
    ctx.move_to ( w/2 - te.x_bearing - te.width / 2,
                  h/2 - fe.descent + fe.height / 2);
    ctx.show_text (_(letter));
    
    style.restore();
    return true;
  }
  
  /* Constructor */
  public CharBox (string letter, Gtk.ShadowType border)
  {
    this.letter = letter;
    this.border = border;
  }
  
  construct
  {
    area = new Gtk.DrawingArea ();
    area.draw.connect(draw_request);
    add (area);
  }
}

