package com.jamshalat.diary

import android.hardware.GeomagneticField
import com.ryanheise.audioservice.AudioServiceActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel

class MainActivity : AudioServiceActivity() {
    companion object {
        private const val GEOMAGNETIC_CHANNEL = "com.jamshalat.diary/geomagnetic"
        private const val DECLINATION_METHOD = "getDeclination"
    }

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, GEOMAGNETIC_CHANNEL)
            .setMethodCallHandler(::handleGeomagneticMethodCall)
    }

    private fun handleGeomagneticMethodCall(call: MethodCall, result: MethodChannel.Result) {
        if (call.method != DECLINATION_METHOD) {
            result.notImplemented()
            return
        }

        val latitude = call.argument<Double>("latitude")
        val longitude = call.argument<Double>("longitude")
        if (latitude == null || longitude == null) {
            result.error("INVALID_ARGS", "Latitude and longitude are required.", null)
            return
        }

        val altitude = call.argument<Double>("altitude") ?: 0.0
        val timestamp = call.argument<Long>("timestamp") ?: System.currentTimeMillis()
        val field = GeomagneticField(
            latitude.toFloat(),
            longitude.toFloat(),
            altitude.toFloat(),
            timestamp,
        )
        result.success(field.declination.toDouble())
    }
}
