pragma Ada_2012;

with GNATCOLL.JSON;  use GNATCOLL.JSON;
with GNATCOLL.Utils; use GNATCOLL.Utils;
with Ada.Exceptions; use Ada.Exceptions;
with Ada.Text_IO;    use Ada.Text_IO;

with Ada.Assertions;

procedure Test_Sorting is
   Obj : JSON_Value := Create_Object;
   Arr : JSON_Array;
   Arc : JSON_Value;

   function Less (Left, Right : JSON_Value) return Boolean is
   begin
      if Left.Kind = Right.Kind then
         case Left.Kind is
         when JSON_String_Type =>
            return String'(Left.Get) < String'(Right.Get);
         when JSON_Int_Type =>
            return Integer'(Left.Get) < Integer'(Right.Get);
         when others =>
            raise Constraint_Error;
         end case;
      else
         return Left.Kind < Right.Kind;
      end if;
   end Less;

   function More (Left, Right : JSON_Value) return Boolean
   is (Less (Right, Left));

begin
   Arc := Create (Arr);

   for J in 1 .. 16 loop
      Append (Arr, Create (J));
      Append (Arr, Create (J'Img));
      Append (Arc, Create (-J));
      Append (Arc, Create (Image (J, 0)));
   end loop;

   Obj.Set_Field ("raw", Arr);

   Sort (Arr, Less'Access);
   Obj.Set_Field ("sorted", Arr);

   Sort (Arc, More'Access);
   Obj.Set_Field ("descend", Arc);

   Put_Line (Write (Obj, Compact => False));

   Obj := Create_Object;

   begin
      Append (Obj, Arc);
      Put_Line ("Unexpected success on append into non array object.");
   exception
      when Constraint_Error | Ada.Assertions.Assertion_Error =>
         --  Expected exception on append to non array object.
         null;
      when E : others =>
         Put_Line ("Unexpected exception: " & Exception_Information (E));
   end;

   for J in 1 .. 16 loop
      Obj.Set_Field (J'Img, 17 - J);
      Obj.Set_Field ('f' & J'Img, J'Img);
   end loop;

   Obj.Sort (Less'Access);

   Put_Line (Write (Obj, Compact => False));
end Test_Sorting;
