(* ::Package:: *)

BeginPackage["graphGuiV3`"]
delegate::usage ="";
output::usage ="";
vertices::usage ="";
edges::usage ="";
vertexLabels::usage ="";
outputGraph::usage ="";
Begin["`Private`"]; 
(* board *)
targetList={};namList={};
boardRatio = 1.4;
boardImageScale = 800;
boardDisable = False;
myStyle = {Medium, FontFamily -> "Helvetica"};
(* graphics-box-class *)
box[nam_] := Module[{textInputMode = False,pos,boxSize,title = Null,arrowLine = {},(* arrow leader *)arrowPointList = {},targetArrowList = {}},
	(* arrows graphics *)
	(* graphics-arrow-class *)
	arrowImage[nam[pointName_]] ^:= Module[{delta,bsize,tpos,arrowDrawback = 0},
		EventHandler[(
			delta = Abs[pos - (tpos = (boxPosGet[pointName]))];
			bsize = 0.5*boxSizeGet[pointName]/(boardRatio*boardImageScale);
			If[delta != {0, 0}, arrowDrawback = Norm[delta]*If[Apply[ArcTan, delta] > Apply[ArcTan, bsize],Abs[bsize[[2]]/delta[[2]]],Abs[bsize[[1]]/delta[[1]]]]];
			{Arrowheads[Medium], Arrow[{pos, boxPosGet[pointName]}, {0, arrowDrawback}]}),
			{"MouseClicked" :> If[CurrentValue["CommandKey"],boxArrowPointDelete[nam[pointName]]]}, PassEventsUp -> False]
			];(* end of arrow class *)						
	boxArrowPointList[nam[pointName_]] ^:= AppendTo[arrowPointList, pointName];
	boxArrowPointDelete[nam[pointName_]] ^:= (arrowPointList = Delete[arrowPointList, Position[arrowPointList, pointName][[1]]]);
	boxPosSet[nam[x_]] ^:= (pos = x);
	boxPosGet[nam] ^:= pos;
	boxTitleSet[nam[x_]] ^:= title = x;
	boxTitleGet[nam] ^:= title;
	boxAPListSet[nam[x_]] ^:= arrowPointList = x;
	boxAPListGet[nam] ^:= arrowPointList;
	boxSizeSet[nam[x_]] ^:= boxSize = x; 
	boxSizeGet[nam] ^:= boxSize; 
	boxBoth[nam] ^:= Which[
		textInputMode == True,(* graphics of text-input-mode *){arrowLine, targetArrowList,
			Text[EventHandler[InputField[Dynamic[title], String, FieldSize -> Small, BaseStyle -> myStyle],
			{"MouseEntered" :> None, "DownArrowKeyDown" :> Paste["\n"],
			"ReturnKeyDown" :> (boardDisable = False; textInputMode = False;
			boxSizeSet[nam[ImageDimensions@Rasterize@Text@Framed[title, FrameMargins -> 5, BaseStyle -> myStyle]]])},PassEventsUp -> False], pos]},
		textInputMode == False,(* graphics-mode *){Dynamic[{arrowLine, targetArrowList}],
			EventHandler[Text[Framed[title, FrameMargins -> 5, BaseStyle -> myStyle], Dynamic[pos], Background -> LightGray],
				{"MouseDragged" :> Switch[CurrentValue["OptionKey"],
					True, (arrowLine = Line[{boxPosGet[nam], MousePosition["Graphics"]}]),
					False, (pos = MousePosition["Graphics"])],(* end of if-current value *)
				"MouseClicked" :> Which[probe[$x[{nam, boardDisable}]];\:3000(* OOP probe program hook line *)
					CurrentValue["CommandKey"], removeInst[nam],
					CurrentValue["ShiftKey"], textInputMode = True; 
					boardDisable = True],
				"MouseMoved" :> (pointName = nam),(* get the name of another instance *)
				"MouseUp" :> Which[
								CurrentValue["OptionKey"],(arrowLine = {};
													boxArrowPointList[nam[pointName]];(* append point to the list *)
													(* overide arrow instances *)
													targetArrowList := Map[arrowImage[nam[#]] &, arrowPointList]),
								True, arrowLine = {}(* safety eraser *)
							],(* end of if-shift-key *)
				PassEventsUp -> False},
			PassEventsUp -> False](* end of event-handler *)
		}(* end of graphics *)
	];(* end of text-input-mode *)
	buildUpArrowList[nam] ^:= targetArrowList := Map[arrowImage[nam[#]] &, arrowPointList]
]; (* end of box-class *)

(* function to make box-instance with unique name *)
makeInst[newPos_] := (newName = Unique[];
	box[newName];(* make new box instance *)
	boxPosSet[newName[newPos]];(* pop-up the instance on the board *)
	boxSizeSet[newName[ImageDimensions@Rasterize@Text@Framed[Null, BaseStyle -> myStyle]]];
	AppendTo[namList, newName];
	targetList := Map[boxBoth, namList](* makeup graphics *));
(* function to remove box-instance *)
removeInst[boxName_] :=(namList = Delete[namList, Position[namList, boxName][[1]]];
	targetList = Map[boxBoth, namList]);

boardGraphics = Graphics[Dynamic[targetList], PlotRange -> {{0, boardRatio}, {0, 1.}}, ImageSize -> {boardRatio, 1}*boardImageScale];

output:=Map[Map[#, namList] &, {List, boxAPListGet, boxTitleGet, boxPosGet, boxSizeGet}];
vertices:=Flatten@First@output;
edges:=DirectedEdge@@#&/@Select[Flatten[Thread[{First@First@#,Last@#}]&/@Transpose@output[[;;2]],1],Length@Union@#==2&];
vertexLabels:=Thread[vertices->output[[3]]];
outputGraph:=Graph[vertices,edges,VertexLabels->vertexLabels]

delegate := Which[boardDisable == True, boardGraphics,
				boardDisable == False,
				EventHandler[boardGraphics, "MouseClicked" :> 
					Which[
						CurrentValue["OptionKey"] == True,
							CreateDialog[
								Pane[
									Column[
									{Button["Save", Put[output,SystemDialogInput["FileSave", FileNameJoin[{Directory[],"graph"}],
										WindowTitle->"Save Graph ..."]];DialogReturn[],Method->"Queued"],
									Button["Load", buildUp[Get[SystemDialogInput["FileOpen", FileNameJoin[{Directory[],"graph"}],
										WindowTitle->"Open Graph ..."]]]; DialogReturn[],Method->"Queued"]}
									],
								ImageMargins -> 5],
							(*Modal -> True,*) WindowTitle -> "objects"],
						(*boardDisable == False,*)
						True, makeInst[MousePosition["Graphics"]]
					],
				PassEventsUp -> False](* end of EventHandler *)
			];(* end of delegate graphics *)
(* build up graphics from file *)
buildUp[{namListX_, boxAPList_, boxTitle_, boxPos_, boxSize_}] := (
	Apply[Clear, namList = Flatten@namListX];
	targetList = {};
	Map[box, namList];
	MapThread[boxPosSet[#1[#2]] &, {namList, boxPos}];
	MapThread[boxSizeSet[#1[#2]] &, {namList, boxSize}];
	MapThread[boxTitleSet[#1[#2]] &, {namList, boxTitle}];
	MapThread[boxAPListSet[#1[#2]] &, {namList, boxAPList}];
	Map[buildUpArrowList, namList]; 
	Flatten@ReleaseHold[MapThread[f[#1, #2] &, {namList, boxAPList}] /. f[nam_, p_] -> Hold@Map[boxArrowPointList[nam, #] &, p]];
	targetList = Map[boxBoth, namList];
	boardDisable = False);
End[]
EndPackage[]



