//+------------------------------------------------------------------+
//|                                                    CalTypes.mqh  |
//|          Data model for the calendar feed (constants and types)  |
//+------------------------------------------------------------------+
#ifndef CAL_TYPES_MQH
#define CAL_TYPES_MQH

//--- data model of the calendar feed: constants, enumerations,
//--- structures and two small helpers that the other files share

//--- time conversion
#define CAL_SECONDS_PER_MINUTE        60      // seconds in one minute
//--- default settings, all three values are heuristics
#define CAL_DEFAULT_BUFFER_MINUTES    15      // buffer of the news window, minutes
#define CAL_DEFAULT_LOOKBACK_MINUTES  720     // loaded range starts 12 hours before the reference time
#define CAL_DEFAULT_HORIZON_MINUTES   4320    // loaded range ends 72 hours after the reference time
//--- array growth
#define CAL_ARRAY_RESERVE             64      // reserve for ArrayResize(), limits reallocations

//--- impact level of an event: the importance value of the terminal
//--- calendar, converted to a type of this package. The impact filter
//--- compares these values, so the numeric order must not change
enum ENUM_CAL_IMPACT
  {
   CAL_IMPACT_NONE     = 0,   // impact level not set
   CAL_IMPACT_LOW      = 1,   // low impact level
   CAL_IMPACT_MODERATE = 2,   // moderate impact level
   CAL_IMPACT_HIGH     = 3    // high impact level
  };

//--- status of the feed and of a query. CAL_STATUS_NOT_REFRESHED is the
//--- initial state, so a feed that was never refreshed cannot pass for
//--- success. Only CAL_STATUS_OK means that the answers can be trusted
enum ENUM_CAL_STATUS
  {
   CAL_STATUS_NOT_REFRESHED     = 0,   // initial state, never counts as success
   CAL_STATUS_OK                = 1,   // last Refresh() succeeded and returned raw records
   CAL_STATUS_NO_DATA           = 2,   // the call succeeded but returned no raw records
   CAL_STATUS_CALL_FAILED       = 3,   // the source reported a failure, see LastError()
   CAL_STATUS_NO_UNIVERSE       = 4,   // no relevant currencies are known
   CAL_STATUS_RANGE_NOT_COVERED = 5,   // the query needs times outside the loaded range
   CAL_STATUS_SYMBOL_UNKNOWN    = 6,   // the symbol is not in the universe
   CAL_STATUS_BAD_ARGUMENT      = 7    // invalid argument, or the source or the clock is missing
  };

//--- treatment of events without an exact time (all-day, no time or
//--- tentative time mode). A heuristic, the reader may choose the other
enum ENUM_CAL_INEXACT_POLICY
  {
   CAL_INEXACT_SKIP    = 0,   // default: drop the event
   CAL_INEXACT_INCLUDE = 1    // keep the event with exact_time set to false
  };

//+------------------------------------------------------------------+
//| CalImpactFromImportance                                          |
//| Converts the importance value of an event                        |
//| (ENUM_CALENDAR_EVENT_IMPORTANCE) to an impact level. A value     |
//| that is not listed gives CAL_IMPACT_NONE.                        |
//+------------------------------------------------------------------+
ENUM_CAL_IMPACT CalImpactFromImportance(const int importance)
  {
   switch(importance)
     {
      case CALENDAR_IMPORTANCE_LOW:
         return(CAL_IMPACT_LOW);
      case CALENDAR_IMPORTANCE_MODERATE:
         return(CAL_IMPACT_MODERATE);
      case CALENDAR_IMPORTANCE_HIGH:
         return(CAL_IMPACT_HIGH);
     }
   return(CAL_IMPACT_NONE);
  }

//+------------------------------------------------------------------+
//| CalImpactToString                                                |
//| Converts an impact level to text for log messages.               |
//+------------------------------------------------------------------+
string CalImpactToString(const ENUM_CAL_IMPACT impact)
  {
   switch(impact)
     {
      case CAL_IMPACT_LOW:
         return("low");
      case CAL_IMPACT_MODERATE:
         return("moderate");
      case CAL_IMPACT_HIGH:
         return("high");
     }
   return("none");
  }

//+------------------------------------------------------------------+
//| CalStatusToString                                                |
//| Converts a status to text for log messages.                      |
//+------------------------------------------------------------------+
string CalStatusToString(const ENUM_CAL_STATUS status)
  {
   switch(status)
     {
      case CAL_STATUS_NOT_REFRESHED:
         return("NOT_REFRESHED");
      case CAL_STATUS_OK:
         return("OK");
      case CAL_STATUS_NO_DATA:
         return("NO_DATA");
      case CAL_STATUS_CALL_FAILED:
         return("CALL_FAILED");
      case CAL_STATUS_NO_UNIVERSE:
         return("NO_UNIVERSE");
      case CAL_STATUS_RANGE_NOT_COVERED:
         return("RANGE_NOT_COVERED");
      case CAL_STATUS_SYMBOL_UNKNOWN:
         return("SYMBOL_UNKNOWN");
      case CAL_STATUS_BAD_ARGUMENT:
         return("BAD_ARGUMENT");
     }
   return("UNKNOWN");
  }

//+------------------------------------------------------------------+
//| CalFloorMinutes                                                  |
//| Minutes as the floor of seconds divided by 60. The operator /    |
//| truncates toward zero, so a negative value with a remainder is   |
//| corrected by one minute. Examples: 901 gives 15, -1 gives -1,    |
//| -60 gives -1 and -61 gives -2.                                   |
//+------------------------------------------------------------------+
int CalFloorMinutes(const long seconds)
  {
   long minutes = seconds / CAL_SECONDS_PER_MINUTE;
//--- the remainder has the sign of the dividend, so it is negative
//--- exactly when the truncated quotient is one minute too high
   if(seconds % CAL_SECONDS_PER_MINUTE < 0)
      minutes--;
   return((int)minutes);
  }

//+------------------------------------------------------------------+
//| CalWindowContains                                                |
//| News window test on seconds, not on rounded minutes. True when   |
//| seconds_to_event lies between -buffer_seconds and +buffer_seconds|
//| and both ends are included.                                      |
//+------------------------------------------------------------------+
bool CalWindowContains(const long seconds_to_event, const long buffer_seconds)
  {
   return(seconds_to_event <= buffer_seconds && seconds_to_event >= -buffer_seconds);
  }

//--- one event of the feed, built from one raw record. The fields
//--- seconds_to_event and minutes_to_event are valid only for the
//--- reference time at which they were computed
struct CCalendarEvent
  {
   ulong             record_id;         // id of the raw record (MqlCalendarValue.id)
   ulong             event_id;          // id of the event description (MqlCalendarValue.event_id)
   datetime          time;              // event time, trade server time
   datetime          period;            // reporting period of the raw record, 0 when none
   int               revision;          // revision number of the raw record
   string            name;              // event name from the event description
   string            currency;          // currency of the country, upper case
   string            country_code;      // country code, for example "US"
   ENUM_CAL_IMPACT   impact;            // impact level
   bool              exact_time;        // false for all-day, no time and tentative time modes
   long              seconds_to_event;  // event time minus reference time, negative after the event
   int               minutes_to_event;  // floor of seconds_to_event divided by 60

                     CCalendarEvent() { Reset(); }   // constructor

   //--- clears every field
   void              Reset()
     {
      record_id        = 0;
      event_id         = 0;
      time             = 0;
      period           = 0;
      revision         = 0;
      name             = "";
      currency         = "";
      country_code     = "";
      impact           = CAL_IMPACT_NONE;
      exact_time       = false;
      seconds_to_event = 0;
      minutes_to_event = 0;
     }
  };

//--- result of a query. The status tells "outside every news window" apart
//--- from "unknown": found and in_window mean something only when the
//--- status is CAL_STATUS_OK
struct SCalendarQuery
  {
   ENUM_CAL_STATUS   status;           // CAL_STATUS_OK only when the query could be answered
   bool              found;            // an event was selected
   bool              in_window;        // result of IsInNewsWindow()
   datetime          reference_time;   // reference time of this answer
   int               buffer_minutes;   // buffer of the news window, minutes
   CCalendarEvent    event;            // selected event, fields computed for reference_time

                     SCalendarQuery() { Reset(); }   // constructor

   //--- clears every field, the status returns to the initial state
   void              Reset()
     {
      status         = CAL_STATUS_NOT_REFRESHED;
      found          = false;
      in_window      = false;
      reference_time = 0;
      buffer_minutes = 0;
      event.Reset();
     }
  };

//--- counters of the last Refresh(): what was read and why raw records
//--- were dropped. Every raw record is counted at most once
struct SCalFeedStats
  {
   int               raw_records;         // raw records returned by the source
   int               lookup_failed;       // dropped: the event or country lookup failed
   int               below_impact;        // dropped: impact level below the minimum
   int               inexact_time;        // dropped: no time, or no exact time and the policy is skip
   int               other_currency;      // dropped: currency is not a relevant currency
   int               duplicates;          // dropped: record id already stored
   int               revisions_dropped;   // dropped: stored event has an equal or higher revision
   int               revisions_replaced;  // stored events replaced by a higher revision

   //--- sets every counter to zero
   void              Reset()
     {
      raw_records        = 0;
      lookup_failed      = 0;
      below_impact       = 0;
      inexact_time       = 0;
      other_currency     = 0;
      duplicates         = 0;
      revisions_dropped  = 0;
      revisions_replaced = 0;
     }
  };

#endif // CAL_TYPES_MQH
//+------------------------------------------------------------------+