#include <bass.h>
#include "SM_Sound.h"



namespace SM_Sound
{
  DWORD g_CurrentStream = 0;
  float g_fTime = -1.0f;
  float g_fBeatPeakFrequency = 0.0f;
  float g_fBeatMinAmplitude = 1.0f;
  bool  g_bInBeat = false;
  float g_fData[SM_SOUND_DATASAMPLES];


  int       Init()
  {
    
    return 0;
  }

  int       Shutdown()
  {
    return 0;
  }
  
  void       SetStream(DWORD handle)
  {
    g_CurrentStream = handle;
  }

  bool      IsBeat           (float fTime)
  {
    float* pfData = 0;
    bool bBeat = false;
    
    if (GetFFT(fTime, pfData))
    {
      int iTest = min(SM_SOUND_DATASAMPLES, max(0, int(g_fBeatPeakFrequency*float(SM_SOUND_DATASAMPLES))));
      int i;

      for (i = 0 ; i < iTest ; i++)
      {
        if (pfData[i] > g_fBeatMinAmplitude)
        {
          bBeat = true;
        }
      }

      if (bBeat)
      {
        g_bInBeat = true;
        return true;
      }
      else
      {
        g_bInBeat = false;
        return false;
      }      
    }

    return false;
  }

  void      SetBeatThreshold (float fPeakFrequency, float fMinAmplitude)
  {
    g_fBeatPeakFrequency = fPeakFrequency;
    g_fBeatMinAmplitude  = fMinAmplitude;  
  }

  void      GetBeatThreshold (float* pfPeakFrequency, float* pfMinAmplitude)
  {
    if (pfPeakFrequency)
    {
      *pfPeakFrequency = g_fBeatPeakFrequency;      
    }

    if (pfMinAmplitude)
    {
      *pfMinAmplitude = g_fBeatMinAmplitude; 
    }
  }

  bool      GetFFT           (float fTime, float*& pfData)
  {
    if (fTime != g_fTime && g_CurrentStream)
    {
      if (BASS_ChannelGetData(
                g_CurrentStream,
                g_fData, 
                BASS_DATA_FFT2048) == -1)
      {
        return false;
      }
    
      g_fTime = fTime;
    }

    pfData = g_fData;
      
    return true;
  }
}  