package dev.kaderli.magsend.activity

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import kotlin.math.pow
import kotlin.math.sqrt

abstract class BaseSensorActivity : BaseActivity(), SensorEventListener {
  private lateinit var sensorManager: SensorManager;
  private lateinit var sensor: Sensor;

  override fun onResume() {
    super.onResume()
    sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
    sensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);
  }

  override fun onStop() {
    super.onStop()
    sensorManager.unregisterListener(this, sensor)
  }

  override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}

  override fun onSensorChanged(event: SensorEvent) {
    val magneticFieldStrength = sqrt(event.values[0].pow(2) + event.values[1].pow(2) + event.values[2].pow(2))
    sensorValueReceived(magneticFieldStrength)
  }

  abstract fun sensorValueReceived(magneticFieldStrength: Float)
}
