package tech.xiongweixp.touchaction

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import tech.xiongweixp.touchaction.ui.theme.TouchActionTheme
import java.net.HttpURLConnection
import java.net.URL

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        Log.i("MainActivity", "打开APP")
        Log.i("MainActivity", intent.data.toString())
        setContentView(R.layout.mainlayout)
    }

    private fun hassioRequest(webhookID: String) {
        Thread {
            try {
                val url = URL("http://192.168.31.45:8123/api/webhook/$webhookID")
                val conn = url.openConnection() as HttpURLConnection
                conn.requestMethod = "GET"
                conn.doInput = true
                conn.doOutput = false
                Log.i("MainActivity", "发送get请求：$webhookID" )
                conn.connect()
                val ret = conn.responseCode
                Log.i("MainActivity", "发送 $webhookID 请求成功，返回码：$ret")
                conn.disconnect()
            }
            catch (e: Exception) {
                Log.i("MainActivity", "发送 $webhookID 请求失败")
                Log.i("MainActivity", e.toString())
            }
        }.start()
    }

    private fun dealAction() {
        Log.i("MainActivity", "感应到标签")
        var uri = intent.data
        if (uri!= null) {
            val action = uri!!.lastPathSegment
            Log.i("ActionActivity", "action: $action")
            when (action) {
                "computer" -> {
                    // 电脑
                    hassioRequest("computer")
                }
                "light" -> {
                    // 灯
                    hassioRequest("light")
                }
//                "save" -> {
//                    // 保存
//                }
//                "delete" -> {
//                    // 删除
//                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        Log.i("MainActivity", "resume打开APP")
        Log.i("MainActivity", intent.data.toString())
        dealAction()
    }
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    TouchActionTheme {
        Greeting("Android")
    }
}

