package com.mxn.helper.screenshot

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.mxn.helper.screenshot.helper.AppConfigHelper.Companion.PORT
import com.mxn.helper.screenshot.logcat.LogcatReader
import com.mxn.helper.screenshot.server.WebService
import com.mxn.helper.screenshot.utils.NetworkUtils
import com.mxn.helper.screenshot.utils.NetworkUtils.TYPE_WIFI
import com.mxn.helper.screenshot.utils.WifiUtils


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        supportActionBar?.hide()
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main_v2)

        initView()

        findViewById<Button>(R.id.btn_start).setOnClickListener {
            if (NetworkUtils.isNetworkAvailable(this)) {
                WebService.start(this)
                setStatus()
            } else {
                //请连接网络
                Toast.makeText(this, "请连接网络", Toast.LENGTH_SHORT).show()
            }
        }

        findViewById<Button>(R.id.btn_stop).setOnClickListener {
            WebService.stop(this)
            setStatus()
        }

        setStatus()
    }

    private fun setStatus() {
        if (NetworkUtils.isNetworkAvailable(this)) {
            val type = NetworkUtils.getNetworkType(this)
            findViewById<TextView>(R.id.tv_info).text =
                "欢迎使用TCL截图助手V1.0.0\n\n" + (if (type == TYPE_WIFI) {
                    "当前WIFI为：" + WifiUtils.getConnectedWifiName(this) + "，请连接此WIFI后访问如下地址："
                } else {
                    "当前连接的为有线网络，请连接与此有线网络的同一局域网后访问如下地址："
                }) + "\n" + NetworkUtils.getIPAddress(
                    this
                ).map { "http://" + it + ":" + PORT }.joinToString("\n") { it } + "\n" + "当前服务状态：" + getStatus()
        } else {
            Toast.makeText(this, "请连接网络", Toast.LENGTH_SHORT).show()
            findViewById<TextView>(R.id.tv_info).text = "欢迎使用TCL截图助手V1.0.0\n\n" + "请连接网络"
        }
    }

    private fun getStatus(): String {
        return if (WebService.isServiceRunning == 1) "服务已启动" else "服务已关闭"
    }

    override fun onBackPressed() {
        Toast.makeText(this, "为防止服务轻易挂掉，请按HOME键返回主页", Toast.LENGTH_SHORT).show()
    }

    private fun initView() {

    }

}