------------------------------------------------------------------------------
--                                  Log4Ada                                 --
--                                                                          --
--                            Copyright (C) 2007                            --
--                              X. Grave CNRS                               --
--                                                                          --
--  This library is free software; you can redistribute it and/or modify    --
--  it under the terms of the GNU General Public License as published by    --
--  the Free Software Foundation; either version 2 of the License, or (at   --
--  your option) any later version.                                         --
--                                                                          --
--  This library is distributed in the hope that it will be useful, but     --
--  WITHOUT ANY WARRANTY; without even the implied warranty of              --
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU       --
--  General Public License for more details.                                --
--                                                                          --
--  You should have received a copy of the GNU General Public License       --
--  along with this library; if not, write to the Free Software Foundation, --
--  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.          --
--                                                                          --
with Ada.Strings.Unbounded;
with Ada.Task_Identification;
with System;

package body Log4ada.Loggers is

   use Ada.Task_Identification;
   use Ada.Strings.Unbounded;

   procedure Dispatch_Event (Logger : not null access Logger_Type;
                             Event : Events.Event_Type);
   procedure Store_Event (Logger : not null access Logger_Type;
                          Event : Events.Event_Type);

   ---------------
   -- Set_Level --
   ---------------

   procedure Set_Level
     (Logger : not null access Logger_Type;
      New_Level : Level_Type)
   is
   begin
      Logger.Current_Level := New_Level;
   end Set_Level;

   ---------------
   -- Get_Level --
   ---------------

   function Get_Level
     (Logger : not null access Logger_Type)
      return Level_Type
   is
   begin
      return Logger.Current_Level;
   end Get_Level;

   ------------------
   -- Add_Appender --
   ------------------

   procedure Add_Appender
     (Logger : not null access Logger_Type;
      Appender : Appenders.Appender_Class_Access)
   is
   begin
      Append (Logger.Appenders_List, Appender);
   end Add_Appender;

   ---------------
   -- Debug_Out --
   ---------------

   type Struct_Timeval is record
      Seconds : Integer;
      Micro_Seconds : Integer;
   end record;
   pragma Convention (C, Struct_Timeval);

   function Get_Time_Of_Day (Data : access Struct_Timeval;
                             Tz : System.Address := System.Null_Address)
                            return Integer;
   pragma Import (C, Get_Time_Of_Day, "gettimeofday");

   procedure Get_Time_Of_Day (Data : access Struct_Timeval);
   procedure Get_Time_Of_Day (Data : access Struct_Timeval) is
      Fct_Return : Integer;
      C_Code_Problem : exception;
   begin
      Fct_Return := Get_Time_Of_Day (Data);
      if Fct_Return /= 0 then
         raise C_Code_Problem;
      end if;
   end Get_Time_Of_Day;

   procedure Event_Out (Logger : not null access Logger_Type;
                        Event : Events.Event_Type) is
      Timestamp : Integer;
      Time_Value : aliased Struct_Timeval;
   begin
      if Logger.Lock_Delay = 0.0 then
         Logger.Lock.Get;
      else
         select
            Logger.Lock.Get;
         or
            delay Logger.Lock_Delay;
            return;
         end select;
      end if;
      if Logger.Current_Level > Events.Get_Level (Event) then
         Logger.Lock.Release;
         return;
      end if;
      if Is_Empty (Logger.Appenders_List) then
         Logger.Lock.Release;
         raise No_Appender;
      end if;
      Get_Time_Of_Day (Time_Value'Access);
      Timestamp := Time_Value.Seconds;
      if Events.First_Event_Timestamp = 0 then
         Events.First_Event_Timestamp := Timestamp;
      end if;
      Store_Event (Logger, Event);
      Dispatch_Event (Logger, Event);
      Logger.Lock.Release;
   exception
      when others =>
         Logger.Lock.Release;
   end Event_Out;

   procedure Set_Memory_Depth (Logger : not null access Logger_Type;
                               Depth : Natural) is
   begin
      Logger.Depth := Depth;
   end Set_Memory_Depth;

   procedure Memory_Out (Logger : not null access Logger_Type;
                         Level : Level_Type) is
   begin
      if Is_Empty (Logger.Appenders_List) then
         raise No_Appender;
      end if;
      if Logger.Lock_Delay = 0.0 then
         Logger.Lock.Get;
      else
         select
            Logger.Lock.Get;
         or
            delay Logger.Lock_Delay;
            return;
         end select;
      end if;
      for Event of Logger.Events_Vector loop
         if Events.Get_Level (Event.all) >= Level then
            Dispatch_Event (Logger, Event.all);
         end if;
         Events.Free (Event);
      end loop;
      Logger.Events_Vector.Clear;
      Logger.Lock.Release;
   exception
      when No_Appender =>
         raise;
      when others =>
         Logger.Lock.Release;
   end Memory_Out;

   procedure Dispatch_Event (Logger : not null access Logger_Type;
                             Event : Events.Event_Type) is
      Index : Positive;
      List_Length : Positive;
      Appender : Appenders.Appender_Class_Access;
   begin
      Index := First_Index (Logger.Appenders_List);
      List_Length := Integer (Length (Logger.Appenders_List));
      for I in Index .. Index + List_Length - 1 loop
         Appender := Element (Logger.Appenders_List, I);
         Appenders.Append (Appender, Event);
      end loop;
   end Dispatch_Event;

   procedure Store_Event (Logger : not null access Logger_Type;
                          Event : Events.Event_Type) is
      Event_Ptr : Events.Event_Access;
   begin
      if Logger.Depth = 0 then
         null;
      elsif Natural (Logger.Events_Vector.Length) < Logger.Depth then
         Logger.Events_Vector.Append (new Events.Event_Type'(Event));
      elsif Natural (Logger.Events_Vector.Length) = Logger.Depth then
         Event_Ptr := Logger.Events_Vector.First_Element;
         Events.Free (Event_Ptr);
         Logger.Events_Vector.Delete_First;
         Logger.Events_Vector.Append (new Events.Event_Type'(Event));
      end if;
   end Store_Event;

   procedure Logger_Output
     (Logger : not null access Logger_Type;
      Message : String;
      Level : Level_Type;
      Exception_To_Send : Ada.Exceptions.Exception_Occurrence;
      With_Traces : Boolean := True) is
      Event : Events.Event_Type;
      Timestamp : Integer;
      Time_Value : aliased Struct_Timeval;
   begin
      if Logger.Current_Level > Level and Logger.Depth = 0 then
         return;
      end if;
      if Is_Empty (Logger.Appenders_List) then
         raise No_Appender;
      end if;
      if Logger.Lock_Delay = 0.0 then
         Logger.Lock.Get;
      else
         select
            Logger.Lock.Get;
         or
            delay Logger.Lock_Delay;
            return;
         end select;
      end if;
      Get_Time_Of_Day (Time_Value'Access);
      Timestamp := Time_Value.Seconds;
      if Events.First_Event_Timestamp = 0 then
         Events.First_Event_Timestamp := Timestamp;
      end if;
      Event := Events.New_Event (Image (Current_Task),
                                 To_String (Logger.Name),
                                 Level,
                                 Timestamp,
                                 Message,
                                 Exception_To_Send,
                                 With_Traces);
      Store_Event (Logger, Event);
      if Logger.Current_Level > Level then
         Logger.Lock.Release;
         return;
      end if;
      Dispatch_Event (Logger, Event);
      Logger.Lock.Release;
   exception
      when No_Appender =>
         raise;
      when others =>
         Logger.Lock.Release;
   end Logger_Output;

   procedure Logger_Output
     (Logger : not null access Logger_Type;
      Message : String;
      Level : Level_Type) is
      Event : Events.Event_Type;
      Timestamp : Integer;
      Time_Value : aliased Struct_Timeval;
   begin
      if Logger.Current_Level > Level and Logger.Depth = 0 then
         return;
      end if;
      if Is_Empty (Logger.Appenders_List) then
         raise No_Appender;
      end if;
      if Logger.Lock_Delay = 0.0 then
         Logger.Lock.Get;
      else
         select
            Logger.Lock.Get;
         or
            delay Logger.Lock_Delay;
            return;
         end select;
      end if;
      Get_Time_Of_Day (Time_Value'Access);
      Timestamp := Time_Value.Seconds;
      if Events.First_Event_Timestamp = 0 then
         Events.First_Event_Timestamp := Timestamp;
      end if;
      Event := Events.New_Event (Image (Current_Task),
                                 To_String (Logger.Name),
                                 Level,
                                 Timestamp,
                                 Message);
      Store_Event (Logger, Event);
      if Logger.Current_Level > Level then
         Logger.Lock.Release;
         return;
      end if;
      Dispatch_Event (Logger, Event);
      Logger.Lock.Release;
   exception
      when No_Appender =>
         raise;
      when others =>
         Logger.Lock.Release;
   end Logger_Output;

   procedure Set_Lock_Delay (Logger : not null access Logger_Type;
                             Lock_Delay : Duration) is
   begin
      Logger.Lock_Delay := Lock_Delay;
   end Set_Lock_Delay;

   procedure Debug_Out
     (Logger : not null access Logger_Type;
      Message : String;
      Exception_To_Send : Ada.Exceptions.Exception_Occurrence;
      With_Traces : Boolean := True) is
   begin
      Logger_Output (Logger, Message, Debug, Exception_To_Send, With_Traces);
   end Debug_Out;

   --------------
   -- Info_Out --
   --------------

   procedure Info_Out
     (Logger : not null access Logger_Type;
      Message : String;
      Exception_To_Send : Ada.Exceptions.Exception_Occurrence;
      With_Traces : Boolean := True)
   is
   begin
      Logger_Output (Logger, Message, Info, Exception_To_Send, With_Traces);
   end Info_Out;

   --------------
   -- Warn_Out --
   --------------

   procedure Warn_Out
     (Logger : not null access Logger_Type;
      Message : String;
      Exception_To_Send : Ada.Exceptions.Exception_Occurrence;
      With_Traces : Boolean := True)
   is
   begin
      Logger_Output (Logger, Message, Warn, Exception_To_Send, With_Traces);
   end Warn_Out;

   ---------------
   -- Error_Out --
   ---------------

   procedure Error_Out
     (Logger : not null access Logger_Type;
      Message : String;
      Exception_To_Send : Ada.Exceptions.Exception_Occurrence;
      With_Traces : Boolean := True)
   is
   begin
      Logger_Output (Logger, Message, Error, Exception_To_Send, With_Traces);
   end Error_Out;

   ---------------
   -- Fatal_Out --
   ---------------

   procedure Fatal_Out
     (Logger : not null access Logger_Type;
      Message : String;
      Exception_To_Send : Ada.Exceptions.Exception_Occurrence;
      With_Traces : Boolean := True)
   is
   begin
      Logger_Output (Logger, Message, Fatal, Exception_To_Send, With_Traces);
   end Fatal_Out;

   procedure Debug_Out (Logger : not null access Logger_Type;
                        Message : String) is
   begin
      Logger_Output (Logger, Message, Debug);
   end Debug_Out;

   procedure Info_Out (Logger : not null access Logger_Type;
                       Message : String) is
   begin
      Logger_Output (Logger, Message, Info);
   end Info_Out;

   procedure Warn_Out (Logger : not null access Logger_Type;
                       Message : String) is
   begin
      Logger_Output (Logger, Message, Warn);
   end Warn_Out;

   procedure Error_Out (Logger : not null access Logger_Type;
                        Message : String) is
   begin
      Logger_Output (Logger, Message, Error);
   end Error_Out;

   procedure Fatal_Out (Logger : not null access Logger_Type;
                        Message : String) is
   begin
      Logger_Output (Logger, Message, Fatal);
   end Fatal_Out;

   protected body Lock_Type is
      entry Get when Available is
      begin
         Available := False;
      end Get;
      procedure Release is
      begin
         Available := True;
      end Release;
   end Lock_Type;

end Log4ada.Loggers;
