/* -*- Mode: Vala; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 * SPDX-FileCopyrightText: Michael Terry
 */

using GLib;

public class DigitBox : CharBox
{
  public Canvas canvas { get; construct; }
  
  public DigitBox (Canvas canvas, string letter)
  {
    Object(canvas: canvas, letter: letter);
  }
  
  construct
  {
    name = "digitbox"; // all theming is in CharBox.vala
    
    // Set up drag
    var drag = new Gtk.DragSource();
    drag.actions = Gdk.DragAction.MOVE;
    drag.prepare.connect(handle_drag_prepare);
    drag.drag_begin.connect(handle_drag_begin);
    drag.drag_end.connect(handle_drag_end);
    add_controller(drag);
    
    // Translators: If there's a better alternative to Arabic numerals for
    // your language, please use it instead of these digits.  Note
    // that it still has to make sense when used as part of the math puzzle.
    N_("0");
    N_("1");
    N_("2");
    N_("3");
    N_("4");
    N_("5");
    N_("6");
    N_("7");
    N_("8");
    N_("9");
  }
  
  Gdk.ContentProvider handle_drag_prepare(Gtk.DragSource source, double x, double y)
  {
    var letter_val = Value(typeof(string));
    letter_val.set_string(letter);
    return new Gdk.ContentProvider.for_value(letter_val);
  }

  void handle_drag_begin(Gtk.DragSource source, Gdk.Drag drag)
  {
    canvas.set_mode(CanvasMode.DIGIT, this);

    // Draw copy of this widget
    var snap = new Gtk.Snapshot();
    this.snapshot(snap);

    // Calculate point location relative to our drag icon
    double x, y;
    double x_offset, y_offset;

    var native = get_native();
    native.get_surface().get_device_position(drag.device, out x, out y, null);

    native.get_surface_transform(out x_offset, out y_offset);
    x -= x_offset;
    y -= y_offset;

    var window = get_ancestor(typeof(Gtk.Window));
    Graphene.Point offset;
    window.compute_point(this, Graphene.Point.zero(), out offset);
    x += offset.x;
    y += offset.y;

    source.set_icon(snap.to_paintable(null), (int)x, (int)y);

    visible = false;
  }
  
  private void handle_drag_end()
  {
    visible = true;
  }
}

