#include <graph_displayer_canvas.h>
#include <broken_edge.h>
#include <math.h>


bool GraphDisplayerCanvas::on_expose_event(GdkEventExpose *event)
{
  Gnome::Canvas::CanvasAA::on_expose_event(event);
  //usleep(10000);
  //rezoom();
  return true;
}

void GraphDisplayerCanvas::changeEditorialTool(int newtool)
{
  actual_handler.disconnect();

  if(actual_tool==CREATE_EDGE)
    {
	GdkEvent * generated=new GdkEvent();
	generated->type=GDK_BUTTON_RELEASE;
	generated->button.button=3;
	create_edge_event_handler(generated);      
    }

  actual_tool=newtool;

  switch(newtool)
    {
    case MOVE:
      actual_handler=displayed_graph.signal_event().connect(sigc::mem_fun(*this, &GraphDisplayerCanvas::move_event_handler), false);
      break;

      //it has to assigned to canvas, because all the canvas has to be monitored, not only the elements of the already drawn group
    case CREATE_NODE:
      actual_handler=signal_event().connect(sigc::mem_fun(*this, &GraphDisplayerCanvas::create_node_event_handler), false);
      break;

    case CREATE_EDGE:
      actual_handler=displayed_graph.signal_event().connect(sigc::mem_fun(*this, &GraphDisplayerCanvas::create_edge_event_handler), false);
      break;

    case ERASER:
      actual_handler=displayed_graph.signal_event().connect(sigc::mem_fun(*this, &GraphDisplayerCanvas::eraser_event_handler), false);
      break;

    default:
      break;
    }
}

int GraphDisplayerCanvas::get_actual_tool()
{
  return actual_tool;
}

bool GraphDisplayerCanvas::move_event_handler(GdkEvent* e)
{
  switch(e->type)
  {
    case GDK_BUTTON_PRESS:
      //we mark the location of the event to be able to calculate parameters of dragging
      clicked_x=e->button.x;
      clicked_y=e->button.y;
      active_item=(get_item_at(e->button.x, e->button.y));
      active_node=INVALID;
      for (NodeIt i(g); i!=INVALID; ++i)
	{
	  if(nodesmap[i]==active_item)
	    {
	      active_node=i;
	    }
	}
      switch(e->button.button)
	{
	case 3:      
	  isbutton=3;
	  break;
	default:
	  isbutton=1;
	  break;
	}
      break;
    case GDK_BUTTON_RELEASE:
      isbutton=0;
      active_item=NULL;
      active_node=INVALID;
      updateScrollRegion();
      break;
    case GDK_MOTION_NOTIFY:
      //we only have to do sg. if the mouse button is pressed AND the click was on a node that was found in the set of nodes
      if(active_node!=INVALID)
      {
	//new coordinates will be the old values,
	//because the item will be moved to the
	//new coordinate therefore the new movement
	//has to be calculated from here

        double dx=e->motion.x-clicked_x;
        double dy=e->motion.y-clicked_y;

        active_item->move(dx, dy);

        clicked_x=e->motion.x;
        clicked_y=e->motion.y;

	//all the edges connected to the moved point has to be redrawn
        EdgeIt ei;

        g.firstOut(ei,active_node);

        for(;ei!=INVALID;g.nextOut(ei))
        {
            Gnome::Canvas::Points coos;
            double x1, x2, y1, y2;

            nodesmap[g.source(ei)]->get_bounds(x1, y1, x2, y2);
            coos.push_back(Gnome::Art::Point((x1+x2)/2,(y1+y2)/2));

            nodesmap[g.target(ei)]->get_bounds(x1, y1, x2, y2);
            coos.push_back(Gnome::Art::Point((x1+x2)/2,(y1+y2)/2));

	    if(isbutton==3)
	      {
		edgesmap[ei]->set_points(coos);
	      }
	    else
	      {
		edgesmap[ei]->set_points(coos,true);
	      }

	    xy<double> text_pos=edgesmap[ei]->get_arrow_pos();
	    text_pos+=(xy<double>(10,10));
	    edgetextmap[ei]->property_x().set_value(text_pos.x);
	    edgetextmap[ei]->property_y().set_value(text_pos.y);
        }

        g.firstIn(ei,active_node);
        for(;ei!=INVALID;g.nextIn(ei))
        {
            Gnome::Canvas::Points coos;
            double x1, x2, y1, y2;

            nodesmap[g.source(ei)]->get_bounds(x1, y1, x2, y2);
            coos.push_back(Gnome::Art::Point((x1+x2)/2,(y1+y2)/2));

            nodesmap[g.target(ei)]->get_bounds(x1, y1, x2, y2);
            coos.push_back(Gnome::Art::Point((x1+x2)/2,(y1+y2)/2));

	    if(isbutton==3)
	      {
		edgesmap[ei]->set_points(coos);
	      }
	    else
	      {
		edgesmap[ei]->set_points(coos,true);
	      }

	    xy<double> text_pos=edgesmap[ei]->get_arrow_pos();
	    text_pos+=(xy<double>(10,10));
	    edgetextmap[ei]->property_x().set_value(text_pos.x);
	    edgetextmap[ei]->property_y().set_value(text_pos.y);
        }
      }
    default: break;
  }

  return true;
}

bool GraphDisplayerCanvas::create_node_event_handler(GdkEvent* e)
{
  switch(e->type)
    {

      //draw the new node in red at the clicked place
    case GDK_BUTTON_PRESS:
      isbutton=1;

      active_node=NodeIt(g,g.addNode());

      //initiating values corresponding to new node in maps
      

      window_to_world (e->button.x, e->button.y, clicked_x, clicked_y);

      nodesmap[active_node]=new Gnome::Canvas::Ellipse(displayed_graph, clicked_x-20, clicked_y-20, clicked_x+20, clicked_y+20);
      active_item=(Gnome::Canvas::Item *)(nodesmap[active_node]);
      *(nodesmap[active_node]) << Gnome::Canvas::Properties::fill_color("red");
      *(nodesmap[active_node]) << Gnome::Canvas::Properties::outline_color("black");
      (nodesmap[active_node])->show();
      break;

      //move the new node
    case GDK_MOTION_NOTIFY:
      {
	double world_motion_x, world_motion_y;
	GdkEvent * generated=new GdkEvent();
	window_to_world (e->motion.x, e->motion.y, world_motion_x, world_motion_y);
	generated->motion.x=world_motion_x;
	generated->motion.y=world_motion_y;
	generated->type=GDK_MOTION_NOTIFY;
	move_event_handler(generated);      
	break;
      }

      //finalize the new node
    case GDK_BUTTON_RELEASE:
      isbutton=0;
      *active_item << Gnome::Canvas::Properties::fill_color("blue");
      active_item=NULL;
      active_node=INVALID;
      updateScrollRegion();
      break;
    default:
      break;
    }
  return false;
}

bool GraphDisplayerCanvas::create_edge_event_handler(GdkEvent* e)
{
  switch(e->type)
    {
    case GDK_BUTTON_PRESS:
      //in edge creation right button has special meaning
      if(e->button.button!=3)
	{
	  //there is not yet selected node
	  if(active_node==INVALID)
	    {
	      //we mark the location of the event to be able to calculate parameters of dragging
	      clicked_x=e->button.x;
	      clicked_y=e->button.y;
	      active_item=(get_item_at(e->button.x, e->button.y));
	      active_node=INVALID;
	      for (NodeIt i(g); i!=INVALID; ++i)
		{
		  if(nodesmap[i]==active_item)
		    {
		      active_node=i;
		    }
		}
	      //the clicked item is really a node
	      if(active_node!=INVALID)
		{
		  *(nodesmap[active_node]) << Gnome::Canvas::Properties::fill_color("red");
		  isbutton=1;
		}
	      //clicked item was not a node. It could be e.g. edge.
	      else
		{
		  active_item=NULL;
		}
	    }
	  //we only have to do sg. if the mouse button
	  // is pressed already once AND the click was
	  // on a node that was found in the set of 
	  //nodes, and now we only search for the second 
	  //node
	  else
	    {
	      target_item=(get_item_at(e->button.x, e->button.y));
	      Graph::NodeIt target_node=INVALID;
	      for (NodeIt i(g); i!=INVALID; ++i)
		{
		  if(nodesmap[i]==target_item)
		    {
		      target_node=i;
		    }
		}
	      //the clicked item is a node, the edge can be drawn
	      if(target_node!=INVALID)
		{
		  *(nodesmap[target_node]) << Gnome::Canvas::Properties::fill_color("red");

		  //creating new edge
		  active_edge=EdgeIt(g,g.addEdge(active_node, target_node));

		  //initiating values corresponding to new edge in maps
		  mapstorage.init_maps_for_edge(active_edge);
	  
		  //calculating coordinates of new edge
		  Gnome::Canvas::Points coos;
		  double x1, x2, y1, y2;
	  
		  active_item->get_bounds(x1, y1, x2, y2);
		  coos.push_back(Gnome::Art::Point((x1+x2)/2,(y1+y2)/2));

		  target_item->get_bounds(x1, y1, x2, y2);
		  coos.push_back(Gnome::Art::Point((x1+x2)/2,(y1+y2)/2));

		  //drawing new edge
		  edgesmap[active_edge]=new BrokenEdge(displayed_graph, coos, *this);
		  *(edgesmap[active_edge]) << Gnome::Canvas::Properties::fill_color("green");
		  edgesmap[active_edge]->property_width_pixels().set_value(10);

		  //redraw nodes to blank terminations of the new edge
		  target_item->raise_to_top();
		  active_item->raise_to_top();

		  //initializing edge-text as well, to empty string
		  xy<double> text_pos=edgesmap[active_edge]->get_arrow_pos();
		  text_pos+=(xy<double>(10,10));

		  edgetextmap[active_edge]=new Gnome::Canvas::Text(displayed_graph, text_pos.x, text_pos.y, "");
		  edgetextmap[active_edge]->property_fill_color().set_value("black");
		}
	      //clicked item was not a node. it could be an e.g. edge. we do not deal with it furthermore.
	      else
		{
		  target_item=NULL;
		}
	    }
	}
      break;
    case GDK_BUTTON_RELEASE:
      isbutton=0;
      //we clear settings in two cases
      //1: the edge is ready (target_item has valid value)
      //2: the edge creation is cancelled with right button
      if((target_item)||(e->button.button==3))
	{
	  if(active_item)
	    {
	      *active_item << Gnome::Canvas::Properties::fill_color("blue");
	      active_item=NULL;
	    }
	  if(target_item)
	    {
	      *target_item << Gnome::Canvas::Properties::fill_color("blue");
	      target_item=NULL;
	    }
	  active_node=INVALID;
	  active_edge=INVALID;
	}
      break;
    default:
      break;
    }
  return false;
}

bool GraphDisplayerCanvas::eraser_event_handler(GdkEvent* e)
{
  switch(e->type)
    {
    case GDK_BUTTON_PRESS:
      active_item=(get_item_at(e->button.x, e->button.y));
      active_node=INVALID;
      active_edge=INVALID;
      for (NodeIt i(g); i!=INVALID; ++i)
	{
	  if(nodesmap[i]==active_item)
	    {
	      active_node=i;
	    }
	}
      if(active_node==INVALID)
	{
	  for (EdgeIt i(g); i!=INVALID; ++i)
	    {
	      if(edgesmap[i]==active_item)
		{
		  active_edge=i;
		}
	    }
	}
    *active_item << Gnome::Canvas::Properties::fill_color("red");
      break;

    case GDK_BUTTON_RELEASE:
      if(active_item==(get_item_at(e->button.x, e->button.y)))
	{
	  if(active_node!=INVALID)
	    {

	      //collecting edges to delete
	      EdgeIt e;
	      std::set<Graph::Edge> edges_to_delete;

	      g.firstOut(e,active_node);
	      for(;e!=INVALID;g.nextOut(e))
		{
		      edges_to_delete.insert(e);
		}

	      g.firstIn(e,active_node);
	      for(;e!=INVALID;g.nextIn(e))
		{
		      edges_to_delete.insert(e);
		}

	      //deleting collected edges
	      for(std::set<Graph::Edge>::iterator edge_set_it=edges_to_delete.begin();edge_set_it!=edges_to_delete.end();edge_set_it++)
		{
		  delete_item(*edge_set_it);
		}
	      delete_item(active_node);
	    }
	  //a simple edge was chosen
	  else
	    {
	      delete_item(active_edge);
	    }

	  
	}
      //pointer was moved, deletion is cancelled
      else
	{
	  if(active_node!=INVALID)
	    {
	      *active_item << Gnome::Canvas::Properties::fill_color("blue");
	    }
	  else
	    {
	      *active_item << Gnome::Canvas::Properties::fill_color("green");
	    }
	}
      //reseting datas
      active_item=NULL;
      active_edge=INVALID;
      active_node=INVALID;
      break;

    case GDK_MOTION_NOTIFY:
      break;

    default:
      break;
    }
  return true;
}

void GraphDisplayerCanvas::delete_item(NodeIt node_to_delete)
{
  delete(nodesmap[node_to_delete]);
  g.erase(node_to_delete);
}

void GraphDisplayerCanvas::delete_item(EdgeIt edge_to_delete)
{
  delete(edgesmap[edge_to_delete]);
  g.erase(edge_to_delete);
}

void GraphDisplayerCanvas::delete_item(Graph::Edge edge_to_delete)
{
  delete(edgesmap[edge_to_delete]);
  g.erase(edge_to_delete);
}

void GraphDisplayerCanvas::text_reposition(xy<double> new_place)
{
  new_place+=(xy<double>(10,10));
  edgetextmap[active_edge]->property_x().set_value(new_place.x);
  edgetextmap[active_edge]->property_y().set_value(new_place.y);
}

void GraphDisplayerCanvas::toggle_edge_activity(BrokenEdge* active_bre, bool on)
{
  if(on)
    {
      if(active_edge!=INVALID)
	{
	  std::cout << "ERROR!!!! Valid edge found!" << std::endl;
	}
      else
	{
	  for (EdgeIt i(g); i!=INVALID; ++i)
	    {
	      if(edgesmap[i]==active_bre)
		{
		  active_edge=i;
		}
	    }
	}
    }
  else
    {
      if(active_edge!=INVALID)
	{
	  active_edge=INVALID;
	}
      else
	{
	  std::cout << "ERROR!!!! Invalid edge found!" << std::endl;
	}
    }

}
