//
//--------------------------------
//  Library TimeSpan
//--------------------------------
//
#include "DefinitionSystem.h"
//
// no directive 
//
#include "TimeSpan.h"
//
//-------------------------------------------------------------------------------
//  TimeSpan - Constructor
//-------------------------------------------------------------------------------
CTimeSpan::CTimeSpan(const char* id)
{
  strcpy(FID, id);
  FTimeStart = micros() / 1000.0f;
  FTimeEnd = INIT_TIMESPAN_MS + FTimeStart;
  FOnEvent = 0;
  FState = stsUnknown;
}

CTimeSpan::CTimeSpan(const char* id, DOnEventTimeSpan oneventtimespan)
{
  strcpy(FID, id);
  FTimeStart = micros() / 1000.0f;
  FTimeEnd = INIT_TIMESPAN_MS + FTimeStart;
  FOnEvent = oneventtimespan;
  FState = stsUnknown;
}
//
//-------------------------------------------------------------------------------
//  TimeSpan - Property
//-------------------------------------------------------------------------------
const char* CTimeSpan::StateText(EStateTimeSpan state)
{
  if (stsIdle == state) return "Idle";
  if (stsBusy == state) return "Busy";
  return "Unknown";
}

EStateTimeSpan CTimeSpan::GetState(void)
{
  return FState;
}
void CTimeSpan::SetState(EStateTimeSpan state)
{
  if (state != FState)
  {
    FState = state;
    if (0 != FOnEvent)
    {
      sprintf(FBuffer, "TimeSpan[%s]: %s", FID, StateText(FState));
      FOnEvent(this, FBuffer);
    }
  }
} 
Boolean CTimeSpan::IsIdle(void)
{
  return (stsIdle == FState);
}
Boolean CTimeSpan::IsBusy(void)
{
  return (stsBusy == FState);
}
//
//-------------------------------------------------------------------------------
//  TimeSpan - Method
//-------------------------------------------------------------------------------
Boolean CTimeSpan::Open()
{
  SetState(stsIdle);
  return true;
}
Boolean CTimeSpan::Close()
{
  SetState(stsIdle);
  return true;
}

Float32 CTimeSpan::GetPeriod(void)
{
  return FTimeEnd - FTimeStart;
}
void CTimeSpan::StartPeriod(Float32 timeperiod) // [mm.uu]
{
  FTimeStart = micros() / 1000.0f;
  FTimeEnd = timeperiod + FTimeStart;
  // debug Serial.println(FTimeStart);
  // debug Serial.println(FTimeEnd);
  SetState(stsBusy);
}
  
void CTimeSpan::Abort(void)
{
  SetState(stsIdle);
}
//
//-------------------------------------------------------------------------------
//  TimeSpan - Execute
//-------------------------------------------------------------------------------
Boolean CTimeSpan::Execute(void)
{
  switch (FState)
  {
    case stsIdle:
      return false;
    case stsBusy:
      // debug Serial.println(FTimeStart);
      // debug Serial.println(FTimeEnd);
      // debug Serial.println((Float32)micros() / 1000.0f - FTimeStart);
      // debug delay(2000);
      if (FTimeEnd <= (Float32)micros() / 1000.0f)
      {
        SetState(stsIdle);
        return true;
      }
      return false;
    default:
      return false;
  }
}
//
