799985fdc417161124c4339b77dacee33a093e1c
[potlatch2.git] / net / systemeD / halcyon / connection / Connection.as
1 package net.systemeD.halcyon.connection {
2
3     import flash.net.*;
4
5     import flash.events.EventDispatcher;
6     import flash.events.Event;
7         import net.systemeD.halcyon.Globals;
8         import net.systemeD.halcyon.connection.actions.*;
9
10         public class Connection extends EventDispatcher {
11
12         private static var connectionInstance:Connection = null;
13
14         protected static var policyURL:String;
15         protected static var apiBaseURL:String;
16         protected static var params:Object;
17
18         public static function getConnection(initparams:Object=null):Connection {
19             if ( connectionInstance == null ) {
20             
21                 params = initparams == null ? new Object() : initparams;
22                 policyURL = getParam("policy", "http://127.0.0.1:3000/api/crossdomain.xml");
23                 apiBaseURL = getParam("api", "http://127.0.0.1:3000/api/0.6/");
24                 var connectType:String = getParam("connection", "XML");
25                 
26                 if ( connectType == "XML" )
27                     connectionInstance = new XMLConnection();
28                 else if ( connectType == "OSM" )
29                     connectionInstance = new OSMConnection();
30                 else
31                     connectionInstance = new AMFConnection();
32             }
33             return connectionInstance;
34         }
35
36         public static function getParam(name:String, defaultValue:String):String {
37             return params[name] == null ? defaultValue : params[name];
38         }
39
40         public function get apiBase():String {
41             return apiBaseURL;
42         }
43
44         public static function get serverName():String {
45             return getParam("serverName", "Localhost");
46         }
47                 
48                 public static function getConnectionInstance():Connection {
49             return connectionInstance;
50                 }
51
52                 public function getEnvironment(responder:Responder):void {}
53
54         // connection events
55         public static var LOAD_STARTED:String = "load_started";
56         public static var LOAD_COMPLETED:String = "load_completed";
57         public static var SAVE_STARTED:String = "save_started";
58         public static var SAVE_COMPLETED:String = "save_completed";
59         public static var DATA_DIRTY:String = "data_dirty";
60         public static var DATA_CLEAN:String = "data_clean";
61         public static var NEW_CHANGESET:String = "new_changeset";
62         public static var NEW_CHANGESET_ERROR:String = "new_changeset_error";
63         public static var NEW_NODE:String = "new_node";
64         public static var NEW_WAY:String = "new_way";
65         public static var NEW_RELATION:String = "new_relation";
66         public static var NEW_POI:String = "new_poi";
67         public static var NODE_RENUMBERED:String = "node_renumbered";
68         public static var WAY_RENUMBERED:String = "way_renumbered";
69         public static var RELATION_RENUMBERED:String = "relation_renumbered";
70         public static var TAG_CHANGED:String = "tag_change";
71         public static var NODE_MOVED:String = "node_moved";
72         public static var WAY_NODE_ADDED:String = "way_node_added";
73         public static var WAY_NODE_REMOVED:String = "way_node_removed";
74         public static var WAY_REORDERED:String = "way_reordered";
75         public static var WAY_DRAGGED:String = "way_dragged";
76                 public static var NODE_DELETED:String = "node_deleted";
77                 public static var WAY_DELETED:String = "way_deleted";
78                 public static var RELATION_DELETED:String = "relation_deleted";
79                 public static var RELATION_MEMBER_ADDED:String = "relation_member_added";
80                 public static var RELATION_MEMBER_REMOVED:String = "relation_member_deleted";
81                 public static var ADDED_TO_RELATION:String = "added_to_relation";
82                 public static var REMOVED_FROM_RELATION:String = "removed_from_relation";
83                 public static var SUSPEND_REDRAW:String = "suspend_redraw";
84                 public static var RESUME_REDRAW:String = "resume_redraw";
85         public static var TRACES_LOADED:String = "traces_loaded";
86
87         // store the data we download
88         private var negativeID:Number = -1;
89         private var nodes:Object = {};
90         private var ways:Object = {};
91         private var relations:Object = {};
92         private var pois:Array = [];
93         private var changeset:Changeset = null;
94                 private var changesetUpdated:Number;
95                 private var modified:Boolean = false;
96                 public var nodecount:int=0;
97                 public var waycount:int=0;
98                 public var relationcount:int=0;
99         private var traces:Array = [];
100         public var nodePositions:Object = {};
101         protected var traces_loaded:Boolean = false;
102
103         protected function get nextNegative():Number {
104             return negativeID--;
105         }
106
107         protected function setNode(node:Node, queue:Boolean):void {
108                         if (!nodes[node.id]) { nodecount++; }
109             nodes[node.id] = node;
110             var a:String = node.lat+","+node.lon
111             if(!nodePositions[a]) {
112               nodePositions[a] = [];
113             }
114             nodePositions[a].push(node.id);
115             if (node.loaded) { sendEvent(new EntityEvent(NEW_NODE, node),queue); }
116         }
117
118         protected function setWay(way:Way, queue:Boolean):void {
119                         if (!ways[way.id]) { waycount++; }
120             ways[way.id] = way;
121             if (way.loaded) { sendEvent(new EntityEvent(NEW_WAY, way),queue); }
122         }
123
124         protected function setRelation(relation:Relation, queue:Boolean):void {
125                         if (!relations[relation.id]) { relationcount++; }
126             relations[relation.id] = relation;
127             if (relation.loaded) { sendEvent(new EntityEvent(NEW_RELATION, relation),queue); }
128         }
129
130         protected function renumberNode(oldID:Number, node:Node, queue:Boolean):void {
131             nodes[node.id] = node;
132             if (node.loaded) { sendEvent(new EntityRenumberedEvent(NODE_RENUMBERED, node, oldID),queue); }
133             delete nodes[oldID];
134         }
135
136         protected function renumberWay(oldID:Number, way:Way, queue:Boolean):void {
137             ways[way.id] = way;
138             if (way.loaded) { sendEvent(new EntityRenumberedEvent(WAY_RENUMBERED, way, oldID),queue); }
139             delete ways[oldID];
140         }
141
142         protected function renumberRelation(oldID:Number, relation:Relation, queue:Boolean):void {
143             relations[relation.id] = relation;
144             if (relation.loaded) { sendEvent(new EntityRenumberedEvent(RELATION_RENUMBERED, relation, oldID),queue); }
145             delete relations[oldID];
146         }
147
148
149                 public function sendEvent(e:*,queue:Boolean):void {
150                         // queue is only used for AMFConnection
151                         dispatchEvent(e);
152                 }
153
154         public function registerPOI(node:Node):void {
155             if ( pois.indexOf(node) < 0 ) {
156                 pois.push(node);
157                 sendEvent(new EntityEvent(NEW_POI, node),false);
158             }
159         }
160
161         public function unregisterPOI(node:Node):void {
162             var index:uint = pois.indexOf(node);
163             if ( index >= 0 ) {
164                 pois.splice(index,1);
165             }
166         }
167
168         public function getNode(id:Number):Node {
169             return nodes[id];
170         }
171
172         public function getWay(id:Number):Way {
173             return ways[id];
174         }
175
176         public function getRelation(id:Number):Relation {
177             return relations[id];
178         }
179
180                 // Remove data from Connection
181                 // These functions are used only internally to stop redundant data hanging around
182                 // (either because it's been deleted on the server, or because we have panned away
183                 //  and need to reduce memory usage)
184
185                 protected function killNode(id:Number):void {
186                         if (!nodes[id]) return;
187             nodes[id].dispatchEvent(new EntityEvent(Connection.NODE_DELETED, nodes[id]));
188                         if (nodes[id].parentRelations.length>0) {
189                                 nodes[id]=new Node(id,0,{},false,0,0);
190                         } else {
191                                 delete nodes[id];
192                         }
193                         nodecount--;
194                 }
195
196                 protected function killWay(id:Number):void {
197                         if (!ways[id]) return;
198             ways[id].dispatchEvent(new EntityEvent(Connection.WAY_DELETED, ways[id]));
199                         if (ways[id].parentRelations.length>0) {
200                                 ways[id]=new Way(id,0,{},false,[]);
201                         } else {
202                                 delete ways[id];
203                         }
204                         waycount--;
205                 }
206
207                 protected function killRelation(id:Number):void {
208                         if (!relations[id]) return;
209             relations[id].dispatchEvent(new EntityEvent(Connection.RELATION_DELETED, relations[id]));
210                         if (relations[id].parentRelations.length>0) {
211                                 relations[id]=new Relation(id,0,{},false,[]);
212                         } else {
213                                 delete relations[id];
214                         }
215                         relationcount--;
216                 }
217
218                 protected function killWayWithNodes(id:Number):void {
219                         var way:Way=ways[id];
220                         var node:Node;
221                         for (var i:uint=0; i<way.length; i++) {
222                                 node=way.getNode(i);
223                                 if (node.isDirty) { continue; }
224                                 if (node.parentWays.length>1) {
225                                         node.removeParent(way);
226                                 } else {
227                                         killNode(node.id);
228                                 }
229                         }
230                         killWay(id);
231                 }
232                 
233
234
235         public function createNode(tags:Object, lat:Number, lon:Number, performCreate:Function):Node {
236             var node:Node = new Node(nextNegative, 0, tags, true, lat, lon);
237             performCreate(new CreateEntityAction(node, setNode));
238                         //markDirty();
239             return node;
240         }
241
242         public function createWay(tags:Object, nodes:Array, performCreate:Function):Way {
243             var way:Way = new Way(nextNegative, 0, tags, true, nodes.concat());
244             performCreate(new CreateEntityAction(way, setWay));
245                         //markDirty();
246             return way;
247         }
248
249         public function createRelation(tags:Object, members:Array, performCreate:Function):Relation {
250             var relation:Relation = new Relation(nextNegative, 0, tags, true, members.concat());
251             performCreate(new CreateEntityAction(relation, setRelation));
252                         //markDirty();
253             return relation;
254         }
255
256         public function getAllNodeIDs():Array {
257             var list:Array = [];
258             for each (var node:Node in nodes)
259                 list.push(node.id);
260             return list;
261         }
262
263         public function getAllWayIDs():Array {
264             var list:Array = [];
265             for each (var way:Way in ways)
266                 list.push(way.id);
267             return list;
268         }
269
270         public function getAllRelationIDs():Array {
271             var list:Array = [];
272             for each (var relation:Relation in relations)
273                 list.push(relation.id);
274             return list;
275         }
276
277         public function getMatchingRelationIDs(match:Object):Array {
278             var list:Array = [];
279                         var ok:Boolean;
280             for each (var relation:Relation in relations) {
281                                 ok=true;
282                                 if (relation.deleted) { ok=false; }
283                                 for (var k:String in match) {
284                                         if (!relation.getTagsHash()[k] || relation.getTagsHash()[k]!=match[k]) { ok=false; }
285                                 }
286                                 if (ok) { list.push(relation.id); }
287                         }
288             return list;
289         }
290
291                 public function getObjectsByBbox(left:Number, right:Number, top:Number, bottom:Number):Object {
292                         var o:Object = { poisInside: [], poisOutside: [], waysInside: [], waysOutside: [] };
293                         for each (var way:Way in ways) {
294                                 if (way.within(left,right,top,bottom)) { o.waysInside.push(way); }
295                                                                   else { o.waysOutside.push(way); }
296                         }
297                         for each (var poi:Node in pois) {
298                                 if (poi.within(left,right,top,bottom)) { o.poisInside.push(poi); }
299                                                                   else { o.poisOutside.push(poi); }
300                         }
301                         return o;
302                 }
303
304                 public function purgeOutside(left:Number, right:Number, top:Number, bottom:Number):void {
305                         for each (var way:Way in ways) {
306                                 if (!way.within(left,right,top,bottom) && !way.isDirty) {
307                                         killWayWithNodes(way.id);
308                                 }
309                         }
310                         for each (var poi:Node in pois) {
311                                 if (!poi.within(left,right,top,bottom) && !poi.isDirty) {
312                                         killNode(poi.id);
313                                 }
314                         }
315                         // ** should purge relations too, if none of their members are on-screen
316                 }
317
318                 public function markDirty():void {
319             if (!modified) { dispatchEvent(new Event(DATA_DIRTY)); }
320                         modified=true;
321                 }
322                 public function markClean():void {
323             if (modified) { dispatchEvent(new Event(DATA_CLEAN)); }
324                         modified=false;
325                 }
326                 public function get isDirty():Boolean {
327                         return modified;
328                 }
329
330                 // Changeset tracking
331
332         protected function setActiveChangeset(changeset:Changeset):void {
333             this.changeset = changeset;
334                         changesetUpdated = new Date().getTime();
335             sendEvent(new EntityEvent(NEW_CHANGESET, changeset),false);
336         }
337
338                 protected function freshenActiveChangeset():void {
339                         changesetUpdated = new Date().getTime();
340                 }
341                 
342                 protected function closeActiveChangeset():void {
343                         changeset = null;
344                 }
345         
346         public function getActiveChangeset():Changeset {
347                         if (changeset && (new Date().getTime()) > (changesetUpdated+58*60*1000)) {
348                                 closeActiveChangeset();
349                         }
350             return changeset;
351         }
352
353         protected function addTrace(t:Object):void {
354             traces.push(t);
355         }
356
357         protected function clearTraces():void {
358             traces = [];
359         }
360
361         public function getTraces():Array {
362             return traces;
363         }
364
365         // these are functions that the Connection implementation is expected to
366         // provide. This class has some generic helpers for the implementation.
367                 public function loadBbox(left:Number, right:Number,
368                                                                 top:Number, bottom:Number):void {
369             }
370             
371             public function setAuthToken(id:Object):void {}
372         public function setAccessToken(key:String, secret:String):void {}
373             public function createChangeset(tags:Object):void {}
374                 public function closeChangeset():void {}
375             public function uploadChanges():void {}
376         public function fetchUserTraces(refresh:Boolean=false):void {}
377         public function fetchTrace(id:Number, callback:Function):void {}
378         public function hasAccessToken():Boolean { return false; }
379     }
380
381 }
382