package com.wirelesstextsyncer.wireless_text_syncer_android

import android.util.Log
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.android.FlutterActivity
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel

class MainActivity : FlutterActivity() {
    private val tag = "WTS"
    private val connectionChannel = "wireless_text_syncer/connection"
    private val connectionStateChannel = "wireless_text_syncer/connection_state"

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, connectionChannel)
            .setMethodCallHandler { call, result ->
                when (call.method) {
                    "connect" -> {
                        val host = call.argument<String>("host").orEmpty()
                        val port = call.argument<Int>("port") ?: 8181
                        val name = call.argument<String>("name").orEmpty()
                        Log.d(tag, "MethodChannel connect host=$host port=$port name=$name")
                        try {
                            ConnectionService.connect(this, host, port, name)
                            result.success(null)
                        } catch (exception: Exception) {
                            Log.e(tag, "MethodChannel connect failed", exception)
                            result.error("CONNECT_FAILED", exception.message, null)
                        }
                    }
                    "disconnect" -> {
                        Log.d(tag, "MethodChannel disconnect")
                        ConnectionService.disconnect(this)
                        result.success(null)
                    }
                    "sendText" -> {
                        val text = call.argument<String>("text").orEmpty()
                        Log.d(tag, "MethodChannel sendText length=${text.length}")
                        result.success(ConnectionService.sendText(text))
                    }
                    "sendEnter" -> {
                        Log.d(tag, "MethodChannel sendEnter")
                        result.success(ConnectionService.sendEnter())
                    }
                    "sendMute" -> {
                        val muted = call.argument<Boolean>("muted") ?: false
                        Log.d(tag, "MethodChannel sendMute muted=$muted")
                        result.success(ConnectionService.sendMute(muted))
                    }
                    "getState" -> {
                        Log.d(tag, "MethodChannel getState")
                        result.success(ConnectionService.stateMap())
                    }
                    "startDiscovery" -> startDiscovery(result)
                    "stopDiscovery" -> result.success(null)
                    else -> result.notImplemented()
                }
            }

        EventChannel(flutterEngine.dartExecutor.binaryMessenger, connectionStateChannel)
            .setStreamHandler(object : EventChannel.StreamHandler {
                override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
                    ConnectionService.eventSink = events
                    events?.success(ConnectionService.stateMap())
                }

                override fun onCancel(arguments: Any?) {
                    ConnectionService.eventSink = null
                }
            })
    }

    private fun startDiscovery(result: MethodChannel.Result) {
        Thread {
            val devices = DiscoveryClient.discover(applicationContext).map { it.toMap() }

            runOnUiThread {
                Log.d(tag, "Discovery finished count=${devices.size}")
                result.success(devices)
            }
        }.start()
    }
}
