package com.dvox.gifunavi

import android.Manifest
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.annotation.NonNull
import androidx.core.content.ContextCompat
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import android.util.Log

class MainActivity: FlutterActivity() {
    private val CHANNEL = "location"

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(
            flutterEngine.dartExecutor.binaryMessenger,
            CHANNEL
        ).setMethodCallHandler { call, result ->
            when (call.method) {
                "startLocationService" -> {
                    Log.d("MainActivity", "Android: called startLocationService.")
                    //val intent = Intent(this, LocationService::class.java)
                    startLocationService()
                    result.success(null)
                }

                "stopLocationService" -> {
                    Log.d("MainActivity", "Android: called stopLocationService.")
                    //val intent = Intent(this, LocationService::class.java)
                    stopLocationService()
                    result.success(null)
                }

                "isLocationServiceRunning" -> {
                    Log.d("MainActivity", "Android: called isLocationServiceRunnung.")
                    val isRunning = isServiceRunning(LocationService::class.java)
                    result.success(isRunning)
                }

                else -> {
                    result.notImplemented()
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("MainActivity", "Android: onCreate.")

        // 位置情報の権限をリクエストする==> main() の前にコールされるので除外 2024-7-19
        /*
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), PERMISSION_REQUEST_CODE)
        } else {
           // startLocationService() // アプリ起動時にLocationServiceを開始する ==> main.dartで制御する。
        }
         */
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // startLocationService()

                Log.d("MainActivity", "Android: PERMISSION_GRANTED.")
            } else {
                // 位置情報の権限が拒否された場合の処理
                Toast.makeText(this, "Location permission denied.", Toast.LENGTH_SHORT).show()
            }
        }
    }

    companion object {
        private const val PERMISSION_REQUEST_CODE = 1
    }

    private fun startLocationService() {
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED &&
            ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.FOREGROUND_SERVICE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            if (!isServiceRunning(LocationService::class.java)) {
                val intent = Intent(this, LocationService::class.java)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    Log.d("MainActivity", "startForegroundService")
                    startForegroundService(intent)
                } else {
                    Log.d("MainActivity", "startService")
                    startService(intent)
                }
            } else {
                Log.d("MainActivity", "Location service is already running.")
            }
        } else {
            Log.d(
                "MainActivity",
                "Location permission or Foreground service location permission is not granted."
            )
            // 位置情報の権限またはフォアグラウンドサービスの位置情報の権限が許可されていない場合の処理を追加する
            // 例: ユーザーに権限の必要性を説明し、許可を求めるダイアログを表示するなど
        }
    }

    private fun stopLocationService() {
        if (isServiceRunning(LocationService::class.java)) {
            val intent = Intent(this, LocationService::class.java)
            stopService(intent)
        } else {
            Log.d("MainActivity", "Location service is not running.")
        }
    }

    private fun isServiceRunning(serviceClass: Class<*>): Boolean {
        val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        for (service in manager.getRunningServices(Int.MAX_VALUE)) {
            if (serviceClass.name == service.service.className) {
                return true
            }
        }
        return false
    }
}
