
with Ada.Text_IO;

with GNATCOLL.Python;
with GNATCOLL.Scripts.Python;

package body Py_Test is

   use Ada;
   use GNATCOLL;

   Repo     : Scripts.Scripts_Repository;
   Python_L : Scripts.Scripting_Language;

   procedure Handler
     (Data : in out Scripts.Callback_Data'Class; Command : in String);

   -------------
   -- Execute --
   -------------

   procedure Execute (Command : in String) is
      Result : Boolean;
   begin
      Scripts.Execute_Command
        (Python_L, Command, Show_Command => False, Errors => Result);
      pragma Unreferenced (Result);
   end Execute;

   -------------
   -- Handler --
   -------------

   procedure Handler
     (Data : in out Scripts.Callback_Data'Class; Command : in String)
   is
      pragma Unreferenced (Command);

      use type Python.PyObject;

      Python_Data : Scripts.Python.Python_Callback_Data'Class
        renames Scripts.Python.Python_Callback_Data'Class (Data);

      Dict : constant Python.PyObject :=
               Scripts.Python.Get_Param (Python_Data, 2);
      Item : Python.PyObject;
      Key  : Python.PyObject;
      Pos  : Integer := 0;
   begin
      Text_IO.Put_Line ("Dict size:"
        & Integer'Image (Python.PyDict_Size (Dict)));

      Item := Python.PyDict_GetItemString (Dict, "a");
      if Item /= null then
         Text_IO.Put_Line ("Key ""a"" found");
      end if;

      Item := Python.PyDict_GetItemString (Dict, "b");
      if Item /= null then
         Text_IO.Put_Line ("Key ""b"" found");
      end if;

      Item := Python.PyDict_GetItemString (Dict, "foo");
      if Item /= null then
         Text_IO.Put_Line ("Key ""foo"" found");
      end if;

      Text_IO.Put_Line ("Pos = " & Integer'Image (Pos));

      loop
         Python.PyDict_Next (Dict, Pos, Key, Item);
         Text_IO.Put_Line ("Pos = " & Integer'Image (Pos));
         exit when Pos = -1;

         Text_IO.Put_Line ("Current key is """
           & Python.PyString_AsString (Key) & '"');
      end loop;
   end Handler;

   ----------------
   -- Initialize --
   ----------------

   procedure Initialize is
   begin
      Repo := new Scripts.Scripts_Repository_Record;
      Scripts.Python.Register_Python_Scripting (Repo, "TEST");
      Python_L := Scripts.Lookup_Scripting_Language (Repo, "python");

      Scripts.Register_Command
        (Repo,
         Command => "run_test",
         Params  => (Scripts.Param ("arg1"), Scripts.Param ("arg2")),
         Handler => Handler'Access);
   end Initialize;

end Py_Test;
