1 module vision.json.patch.operation.remove;
2 
3 import vision.json.patch.operation.basic;
4 
5 class RemoveOperation : DiffOperation
6 {
7 	import std.json : parseJSON;
8 	
9 	static emptyObject = parseJSON("{}");
10 	override @property string op() pure const @safe { return "remove"; }
11 	
12 	this(T)(T path) @safe
13 	{
14 		super(path);
15 	}
16 
17 	override bool applyToPtr(JsonItem* document) const
18 	{
19 		import std.conv : to;
20 		
21 		if(path.isRoot)
22 		{
23 			*document = emptyObject;
24 			return true;
25 		}
26 		
27 		if(path.evaluate(document).isNull)
28 			return error("No path "~path.toString~" to remove");
29 			
30 		auto parent = path.parent.evaluate(document);
31 		string index = path.lastComponent;
32 		
33 		switch(parent.type)
34 		{
35 			case JSON_TYPE.ARRAY:
36 				try 
37 				{
38 					import std.array: replaceInPlace;
39 					
40 					auto numeric = index.to!int;
41 					if(numeric >= parent.array.length)
42 						return error("Too big index for "~parent.get.toString~", length="~parent.array.length.to!string);
43 					parent.array.replaceInPlace(numeric, numeric+1, cast(JsonItem[])[]);
44 				}
45 				catch(Exception e)
46 				{
47 					return error(parent.get.toString~" is array, index can't be "~index);
48 				}
49 				break;
50 			case JSON_TYPE.OBJECT:
51 				parent.get.object.remove(index);
52 				break;
53 			
54 			default: return error(parent.get.toString ~ " is not array or object");
55 		}
56 		return true;
57 	}
58 
59 }