#include "bike_math.h"
#include "bike_store.h"

uint16_t bikeMathGetValueForDataType(bikeStoreMeasurement measurement, bikeDataType data_type) {
    uint16_t value = 0;

    if (data_type == BIKECADENCE) {
    value = measurement.cadence;
    } else if (data_type == BIKESPEED) {
    value = measurement.speed;
    } else if (data_type == BIKEHEARTRATE) {
    value = measurement.heartRate;
    } else if (data_type == BIKEPOWER) {
    value = measurement.power;
    }

    return value;
}

uint16_t bikeMathCalculateMinValue(bikeDataType data_type) {
    uint16_t number_of_measurements = bikeStoreGetNumberOfMeasurementsPresent();

    uint16_t min_value = UINT16_MAX;

    for (uint16_t index_position = 0; index_position < number_of_measurements; index_position++) {
        bikeStoreMeasurement measurement = bikeStoreGetMeasurement(index_position);
        uint16_t value = bikeMathGetValueForDataType(measurement, data_type);
        if (value < min_value) {
        min_value = value;
        }
    }

    return min_value;
}

uint16_t bikeMathCalculateMaxValue(bikeDataType data_type) {
    uint16_t number_of_measurements = bikeStoreGetNumberOfMeasurementsPresent();

    uint16_t max_value = 0;

    for (uint16_t index_position = 0; index_position < number_of_measurements; index_position++) {
        bikeStoreMeasurement measurement = bikeStoreGetMeasurement(index_position);
        uint16_t value = bikeMathGetValueForDataType(measurement, data_type);
        if (value > max_value) {
            max_value = value;
        }
    }

    return max_value;
}

uint16_t bikeMathCalculateAverageValue(bikeDataType data_type) {
    uint16_t number_of_measurements = bikeStoreGetNumberOfMeasurementsPresent();

    if (number_of_measurements == 0) return 0;

    uint16_t average = 0;
    uint32_t sum = 0;

    for (uint16_t index_position = 0; index_position < number_of_measurements; index_position++) {
        bikeStoreMeasurement measurement = bikeStoreGetMeasurement(index_position);
        uint16_t value = bikeMathGetValueForDataType(measurement, data_type);
        sum += value;
    }

    average = sum / number_of_measurements;

    return average;
}