package de.sebse.fuplanner2

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import de.sebse.fuplanner2.auth.AppAccounts
import de.sebse.fuplanner2.auth.FuplannerAccountActivity
import de.sebse.fuplanner2.auth.FuplannerAccountConstants
import de.sebse.fuplanner2.utils.Notifications


class StartupActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_startup)
    }

    override fun onStart() {
        super.onStart()

        // has accounts? -> false: goto AccountActivity (add=true) / exit for result
        // get selected account -> false: select other
        // refresh token -> false: goto AccountActivity (add=false, pre-fill username) / exit
        // goto MainActivity


        Notifications.init(applicationContext)
        val accounts = AppAccounts.getInstance()
        val selectedAccount = accounts.selectedAccount
        if (selectedAccount == null) {
            val intent = FuplannerAccountActivity.createIntent(
                this,
                true,
                FuplannerAccountConstants.FU_ACC_TYPE
            )
            startActivityForResult(intent, LAUNCH_LOGIN_RESULT)
        } else {
            accounts.refresh(selectedAccount) {
                when (it) {
                    AppAccounts.RefreshResults.UNSPECIFIED_ERROR,
                    AppAccounts.RefreshResults.NETWORK_ERROR,
                    AppAccounts.RefreshResults.SUCCESS -> {
                        AppAccounts.getInstance().setPeriodicSync()
                        val intent = Intent(this, MainActivity::class.java)
                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
                        if (it == AppAccounts.RefreshResults.NETWORK_ERROR)
                            intent.putExtra(MainActivity.EXTRA_NETWORK_ERROR, true)
                        if (it == AppAccounts.RefreshResults.UNSPECIFIED_ERROR)
                            intent.putExtra(MainActivity.EXTRA_UNSPECIFIED_ERROR, true)
                        startActivity(intent)
                    }
                    AppAccounts.RefreshResults.INVALID_PASSWORD -> {
                        val intent = FuplannerAccountActivity.createIntent(
                            this,
                            true,
                            accountType = selectedAccount.type,
                            accountName = selectedAccount.name
                        )
                        startActivity(intent)
                    }
                }
                finish()
            }
        }
    }

    companion object {
        const val LAUNCH_LOGIN_RESULT = 111
    }
}
