package club.clubk.ktag.apps.mqttbroker

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import club.clubk.ktag.apps.sharedservices.SharedMqttClient

class BrokerSettingsActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(club.clubk.ktag.apps.sharedservices.R.layout.activity_settings)

        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                .replace(club.clubk.ktag.apps.sharedservices.R.id.settings_container, BrokerSettingsFragment())
                .commit()
        }
    }

    override fun finish() {
        if (MqttBrokerManager.isBrokerEnabled(this)) {
            MqttBrokerManager.startBrokerIfEnabled(this)
        } else {
            MqttBrokerManager.stopBroker(this)
        }
        SharedMqttClient.connect(this)
        super.finish()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    companion object {
        fun createIntent(context: Context): Intent {
            return Intent(context, BrokerSettingsActivity::class.java)
        }
    }
}
