with Ada.Text_IO;  use Ada.Text_IO;

package body Support is

   use Msg_Queues;

   protected body Protected_Queue is
      entry Put (Msg : GNATCOLL.Traces.Msg_Strings.XString)
          when not Is_Full (Q)
      is
         Success : Boolean;
         pragma Unreferenced (Success);
      begin
         Append (Q, Success, Msg);
      end Put;

      entry Get (Msg : out GNATCOLL.Traces.Msg_Strings.XString)
         when not Is_Empty (Q)
      is
         Success : Boolean;
         pragma Unreferenced (Success);
      begin
         Get (Q, Success, Msg);
      end Get;
   end Protected_Queue;

   overriding procedure Put
     (Self       : in out Async_Stream_Record;
      Str        : GNATCOLL.Traces.Msg_Strings.XString)
   is
   begin
      Self.Messages.Put (Str);
   end Put;

   task body Async_Logger is
      Q   : Protected_Queue_Access;
      Msg : GNATCOLL.Traces.Msg_Strings.XString;
      File : File_Type;
      S    : GNATCOLL.Traces.Msg_Strings.Unconstrained_String_Access;
      L    : Natural;
   begin
      accept Init (Buffer : Protected_Queue_Access) do
         Q := Buffer;
      end Init;

      Create (File, Out_File, "foo_async.txt");
      loop
         Q.Get (Msg);
         Msg.Get_String (S, L);
         Put (File, String (S (1 .. L)));
      end loop;
   end Async_Logger;

   overriding function New_Stream
     (Self : Async_Stream_Factory; Args : String)
      return GNATCOLL.Traces.Trace_Stream
   is
      S : access Async_Stream_Record :=
         new Async_Stream_Record;
   begin
      S.Logger := new Async_Logger;
      S.Logger.Init (S.Messages'Access);
      return GNATCOLL.Traces.Trace_Stream (S);
   end New_Stream;

end Support;
