// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include "gtest/gtest.h"
#include "audio/sampling.h"
#include <vector>
#include <cmath>

// The expected test result was generated by the following Python library
// b, a = scipy.signal.butter(4, 8000/(441000/2), btype='low', analog=False)
TEST(ButterworthLowpassTest, CalculateCoefsTest) {
  std::vector<double> expected_b = {
      9.12788e-06,
      3.65115e-05,
      5.47673e-05,
      3.65115e-05,
      9.12788e-06};
  std::vector<double> expected_a = {1.0, -3.70223, 5.15023, -3.19013, 0.742275};

  ButterworthLowpass filt(8000, 441000);
  ASSERT_EQ(filt.GetCoefs_B().size(), expected_b.size()) << "Coefs-B result and expected are of unequal length";
  ASSERT_EQ(filt.GetCoefs_A().size(), expected_a.size()) << "Coefs-A result and expected are of unequal length";
  for (size_t i = 0; i < expected_b.size(); ++i) {
    EXPECT_NEAR(expected_b[i], filt.GetCoefs_B().at(i), 1e-5) << "Coefs-B result and expected differ at index " << i;
    EXPECT_NEAR(expected_a[i], filt.GetCoefs_A().at(i), 1e-5) << "Coefs-A result and expected differ at index " << i;
  }
}

// The expected test result was generated by the following Python library
// data = np.asarray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=np.float32)
// scipy.signal.lfilter(b, a, data)
TEST(ButterworthLowpassTest, FilterTest) {
  std::vector<float> signal = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  std::vector<double> expected = {9.1278764060962e-06, 8.856077402703055e-05, 0.00043603576325860837,
                                  0.0014794083160631888, 0.00394531110456504, 0.008896621026975655,
                                  0.01774416762114977, 0.032237572808636775, 0.05443959732833486, 0.08668788318758487};

  ButterworthLowpass filt(8000, 441000);
  std::vector<float> actual = filt.Process(signal);
  EXPECT_EQ(expected.size(), actual.size());
  for (size_t i = 0; i < actual.size(); i++) {
    EXPECT_NEAR(expected[i], actual[i], 1e-05);
  }
}
