package partisan.weforge.xyz.pulse

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import partisan.weforge.xyz.pulse.databinding.ActivityMainBinding
import androidx.appcompat.app.ActionBarDrawerToggle
import partisan.weforge.xyz.pulse.REQUIRED_PERMISSIONS
import partisan.weforge.xyz.pulse.hasCallRedirectionRole
import partisan.weforge.xyz.pulse.hasDrawOverlays
import partisan.weforge.xyz.pulse.hasGeneralPermissions

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var prefs: Preferences

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setSupportActionBar(binding.topAppBar)

        val drawerToggle = ActionBarDrawerToggle(
            this,
            binding.drawerLayout,
            binding.topAppBar,
            R.string.navigation_drawer_open,
            R.string.navigation_drawer_close
        )
        binding.drawerLayout.addDrawerListener(drawerToggle)
        drawerToggle.syncState()

        supportFragmentManager.beginTransaction()
            .replace(R.id.fragmentContainer, MainFragment())
            .commit()

        binding.navigationView.setNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.action_popup_settings -> {
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.fragmentContainer, PopupSettingsFragment())
                        .addToBackStack(null)
                        .commit()
                    true
                }
                R.id.action_about -> {
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.fragmentContainer, AboutFragment())
                        .addToBackStack(null)
                        .commit()
                    true
                }
                R.id.action_services -> {
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.fragmentContainer, ServiceSettingsFragment())
                        .addToBackStack(null)
                        .commit()
                    true
                }
                R.id.action_contacts -> {
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.fragmentContainer, ContactsFragment())
                        .addToBackStack(null)
                        .commit()
                    true
                }
                else -> false
            }.also {
                binding.drawerLayout.closeDrawers()
            }
        }
    }

    private fun hasPermissions(): Boolean {
        return hasGeneralPermissions(this) &&
               hasDrawOverlays(this) &&
               hasCallRedirectionRole(this)
    }
}
