export const SplashFragment = (configuration) => {
  return `
        
package ${configuration.packageName}.ui.fragments

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import ${configuration.name}.R
import ${configuration.packageName}.data.local.AppPreferences
import ${configuration.packageName}.extensions.Constants
import Manaknight.databinding.FragmentSplashBinding
import androidx.navigation.fragment.findNavController
import ${configuration.packageName}.extensions.viewBinding
import org.koin.android.ext.android.inject
${
configuration.isGoogleLogin
    ? `import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.result.ActivityResult
import android.app.Activity
import android.annotation.SuppressLint
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity

`
    : ""
}
${
  configuration.isAppleLogin
    ? `
import com.google.firebase.auth.OAuthCredential
import com.google.firebase.auth.OAuthProvider
import android.content.ContentValues
`
    : ""
}
${
  configuration.isAppleLogin || configuration.isGoogleLogin
    ? `
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.FirebaseAuth
import ${configuration.name}.databinding.ActivityMainBinding
import ${configuration.name}.BuildConfig
import ${configuration.packageName}.network.Status
import ${configuration.packageName}.viewmodels.BaasViewModel
import ${configuration.packageName}.extensions.snackBar
import ${configuration.packageName}.extensions.showProgressBar
import ${configuration.packageName}.extensions.hideProgressBar
import org.koin.androidx.viewmodel.ext.android.viewModel
import android.util.Log

`
    : ""
}

class SplashFragment : Fragment(R.layout.fragment_splash) {

    private val binding by viewBinding(FragmentSplashBinding::bind)
    private val pref by inject<AppPreferences>()
    ${
      configuration.isAppleLogin || configuration.isGoogleLogin
        ? `
    private val baasViewModel: BaasViewModel by viewModel()
    private val auth = FirebaseAuth.getInstance()
    `
        : ""
    }

    ${
      configuration.isGoogleLogin
        ? `

    private val googleResultLauncher: ActivityResultLauncher<Intent> =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
            if (result.resultCode == Activity.RESULT_OK) {
                val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
                handleSignInResult(task)
            } else {
                val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
                handleSignInResult(task)
                snackBar("Something went wrong")
//                    state = Enums.ToastStates.SAD)
            }
        }
    `
        : ""
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.buttonSplashLogin.setOnClickListener{
            findNavController().navigate(R.id.action_splashFragment_to_loginFragment)
        }

        binding.btnSplashRegister.setOnClickListener{
            findNavController().navigate(R.id.action_splashFragment_to_signUpFragment)
        }

        if (pref.isLoggedIn) {
            Constants.AUTH_TOKEN.value = pref.accessToken
            Constants.isAuthorized.postValue(true)
            findNavController().navigate(R.id.action_splashFragment_to_homeFragment)
        }

         ${
           configuration.isGoogleLogin
             ? `    val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(BuildConfig.GOOGLE_CLIENT_ID)
                .requestServerAuthCode(BuildConfig.GOOGLE_CLIENT_ID)
                .requestEmail()
                .requestProfile()
                .build()
            val googleSignInClient = GoogleSignIn.getClient(requireActivity(), gso)

            binding.btnGoogle.setOnClickListener {
                googleResultLauncher.launch(googleSignInClient.signInIntent)
            }`
             : ""
         }

       ${
         configuration.isAppleLogin
           ? ` binding.btnApple.setOnClickListener {
            val provider = OAuthProvider.newBuilder("apple.com")
            provider.scopes = mutableListOf("email", "name")
            val pending = auth.pendingAuthResult
            if (pending != null) {
                pending.addOnSuccessListener { authResult ->
                    val user = authResult.credential as OAuthCredential
                    handleAppleSignIn("", "", user.idToken.toString(), "", "")
                }.addOnFailureListener { e ->
                    Log.w(ContentValues.TAG, "checkPending:onFailure", e)
                }
            } else {
                Log.d(ContentValues.TAG, "pending: null")
                auth.startActivityForSignInWithProvider(requireActivity(), provider.build())
                    .addOnSuccessListener { authResult ->
                        val user = authResult.credential as OAuthCredential
                        handleAppleSignIn("", "", user.idToken.toString(), "", "")
                    }
                    .addOnFailureListener { e ->
                        Log.w(ContentValues.TAG, "checkPending:onFailure", e)
                    }
            }
        }`
           : ""
       }
    }


  ${
    configuration.isGoogleLogin || configuration.isAppleLogin
      ? ` 
    

    override fun onResume() {
        super.onResume()
        (activity as AppCompatActivity?)!!.supportActionBar!!.hide()

    }

    override fun onDestroy() {
        super.onDestroy()
    } 

    override fun onStop() {
            super.onStop()
            (activity as AppCompatActivity?)!!.supportActionBar!!.show()
    }
    
    private fun redirectAfterLogin() {
        TODO("Not yet implemented")
    }


${
  configuration.isGoogleLogin
    ? `private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
        try {
            val account = completedTask.getResult(ApiException::class.java)
             val code = account.idToken
            val isRefresh = true
            val role = "user"
            if (code != null) {
                loginUser(role, isRefresh, code)
            } else {
                snackBar(
                    getString(R.string.something_went_wrong, getString(R.string.try_again))
                )
            }
        } catch (e: ApiException) {
            snackBar(e.message ?: getString(R.string.something_went_wrong, "")
               )
        }
    }`
    : ""
}
    `
      : ""
  }

  ${
    configuration.isGoogleLogin
      ? ` private fun loginUser(role: String, isRefresh: Boolean, code: String) {
        baasViewModel.googleCodeMobile(role, isRefresh, code).observe(viewLifecycleOwner) {
            when (it.status) {
                Status.ERROR -> {
                    hideProgressBar()
                    snackBar(
                        it.message ?: "Error: Exception not defined",
                        
                    )
                }
                Status.LOADING -> {
                    showProgressBar()
                }
                Status.SUCCESS -> {
                    hideProgressBar()
                    val data = it.data
                    if (data != null && !it.data.error!!) {
                        with(data.user_id) {
                            pref.saveUser(
                                data.user_id?.toInt(), data.token, data.role, "", "", "", ""
                            )
                            redirectAfterLogin()
                        }
                    } else snackBar(   
                        it.data?.message ?: "Login Error",
                        
                    )
                    hideProgressBar()
                }
            }
        }
    }`
      : ""
  }

  ${
    configuration.isAppleLogin
      ? ` private fun handleAppleSignIn( firstName: String, lastName: String, identitytoken: String, appleId: String, role: String) {
        baasViewModel.appleLoginMobileEndpoint( firstName, lastName, identitytoken, appleId, role).observe(viewLifecycleOwner) {
            when (it.status) {
                Status.ERROR -> {
                    snackBar(
                        it.message ?: "Error: Exception not defined",
                    )
                    hideProgressBar()
                }
                Status.LOADING -> {
                    showProgressBar()
                }
                Status.SUCCESS -> {
                    hideProgressBar()
                    val data = it.data
                    if (data != null && !it.data.error!!) {
                        with(data.user_id) {
                            pref.saveUser(
                              data.user_id?.toInt(), data.access_token, data.role, "", "", "", ""
                            )
                            redirectAfterLogin()
                        }
                    } else snackBar(
                        it.data?.message ?: "Login Error",
                        
                    )
                }
            }
        }
    }`
      : ""
  }
}
    
    `;
};
