import { StringCaser } from "@/utils/utils";

export default (configuration) => {
    configuration.navigationType = configuration?.nav;
    if (configuration?.navigationType === "sideBar") {
        configuration.hasToolBar = true;
    } else {
        configuration.hasToolBar = false;
    }
    return `
package ${configuration.packageName}

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.media.MediaCodec.MetricsConstants.MODE
import android.net.Uri
import android.os.Bundle
import android.os.Build
import android.os.Handler
import android.util.Log
import android.Manifest
import android.widget.Toast
import androidx.annotation.IdRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import ${configuration.packageName}.data.local.AppPreferences
import ${configuration.packageName}.extensions.*
import ${configuration.packageName}.extensions.Constants.APP_UPDATE_REQUEST_CODE
import ${configuration.packageName}.extensions.Constants.PERMISSION_REQUEST_ACTIVITY_RECOGNITION
import ${configuration.packageName}.extensions.RequestCodes
import ${configuration.packageName}.extensions.getNotificationPermission

//import ${configuration.packageName}.viewmodels.*
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
import com.google.android.play.core.install.model.AppUpdateType
import com.google.android.play.core.install.model.UpdateAvailability
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.messaging.FirebaseMessaging
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.koin.android.ext.android.inject
import org.koin.androidx.viewmodel.ext.android.viewModel
import android.view.MenuItem
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.drawerlayout.widget.DrawerLayout
import androidx.appcompat.widget.Toolbar
import ${configuration.name}.R
import ${configuration.name}.databinding.ActivityMainBinding
import ${configuration.packageName}.viewmodels.BaasViewModel
import androidx.core.view.GravityCompat

import java.util.*



class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var navController: NavController
    private val baasViewModel: BaasViewModel by viewModel()
    private val pref by inject<AppPreferences>()
    private var actionBarDrawerToggle: ActionBarDrawerToggle? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (Build.VERSION.SDK_INT > 32) {
            if (!shouldShowRequestPermissionRationale(RequestCodes.NOTIFICATION_PERMISSION.toString())){
                getNotificationPermission()
            }
        }

       
        //displayNotification("Alerts", "You have a new message", id = 2);


        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        navController = findNavController(R.id.nav_host_fragment_activity_main)

        binding.myToolbar.setupWithNavController(navController)

       
        ${!configuration.hasToolBar
            ? ""
            : `
             ${configuration?.navigationType === "sideBar" ? `
                actionBarDrawerToggle = ActionBarDrawerToggle(this, binding.activityMain, Manaknight.R.string.nav_open, Manaknight.R.string.nav_close)
                binding.activityMain.addDrawerListener(actionBarDrawerToggle!!)
                actionBarDrawerToggle!!.syncState()
                supportActionBar?.setDisplayHomeAsUpEnabled(true)
                supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_menu)
        ` : ""}

            
            val toolbar: Toolbar = findViewById(R.id.my_toolbar)
            setSupportActionBar(toolbar)
            
            supportActionBar?.apply {
                title = "${configuration.name}"
                setDisplayHomeAsUpEnabled(true) 
             ${configuration?.navigationType === "sideBar"
                ? `setHomeAsUpIndicator(R.drawable.ic_menu)`
                : ""
            }

            binding.navView.setNavigationItemSelectedListener {
                val id = it.itemId

                if (id == R.id.home) {
                    navController.popBackStack()
                }${configuration?.menu?.map((item) => item?.destination == "home" ? "" : `
                   else if (id == R.id.${item?.destination}) {
                    navigateOnce(R.id.action_HomeFragment_to_${StringCaser(item?.destination, { casetype: "PascalCase" })}Fragment)
                    }
                `).join('\n')}
                
    
                binding.activityMain.closeDrawer(GravityCompat.START)
                return@setNavigationItemSelectedListener true;
            }
            
        }
      `
        }

     ${configuration?.navigationType === "bottomBar"
            ? ` 
            navController.addOnDestinationChangedListener { _, destination, _ ->
                when (destination.id) {               
                    ${configuration?.menu
                ?.map(
                    (bar) =>
                        `R.id.${bar.destination} -> {
                        binding.navView.show()
                          ${configuration?.appBar?.length > 0 ? `
                            binding.myToolbar.show()
                            supportActionBar?.title = "${bar.title}"
                        ` : ""
                        }
                        
                    }`
                )
                .join("\n")}
                    else -> {
                        binding.navView.hide()
                          ${configuration?.appBar?.length > 0 ? `
                            binding.myToolbar.hide()
                            supportActionBar?.title = "${configuration?.projectId}"
                        ` : ""
            }
                        
                    }
                }
            }

        binding.navView.setOnNavigationItemSelectedListener { menuItem ->
            navigateOnce(menuItem.itemId)
            true
        }
        
        `
            : ""
        }

        ${configuration?.appBar?.length > 0
            ? `
            setSupportActionBar(binding.myToolbar)
            supportActionBar?.setDisplayHomeAsUpEnabled(true)
        ` : ""
        }

        checkLatestVersion()
        
        observeAuthorization()
    }

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

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

    private fun observeAuthorization() {
        Constants.isAuthorized.observe(this) { authorized ->
            if (!authorized) {
                pref.logout()
                navController.navigate(R.id.splash)
            }
        }
    }

    private fun checkLatestVersion() {
        val appUpdateManager = AppUpdateManagerFactory.create(this)
        val appUpdateInfoTask = appUpdateManager.appUpdateInfo
        appUpdateInfoTask.addOnSuccessListener { appUpdateInfo ->
            if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
                && appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)
            ) {
                //Notify that new update is available
                appUpdateManager.startUpdateFlowForResult(
                    appUpdateInfo,
                    AppUpdateType.IMMEDIATE,
                    this,
                    APP_UPDATE_REQUEST_CODE
                )
            }
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == APP_UPDATE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // Notify Update Complete
            } else {
                // Notify Update Failed
            }
        }
    }

    private fun updateFcmToken() {
        FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
            if (!task.isSuccessful) {
                Log.d(ContentValues.TAG, "Fetching FCM registration token failed", task.exception)
                return@OnCompleteListener
            }
            val token = task.result
            val msg = token.toString()
            pref.fcmToken = msg
            Log.v(ContentValues.TAG, msg)

            //syncUserDevice()
        })
    }

    private fun navigateOnce(@IdRes resId: Int) {
        if (navController.currentDestination?.id != resId) {
            navController.navigate(resId)
        }
    }

    fun askForCameraPermission() {
        ActivityCompat.requestPermissions(
            this, arrayOf(android.Manifest.permission.CAMERA), RequestCodes.CAMERA_PERMISSION
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            RequestCodes.NOTIFICATION_PERMISSION -> {
                if (grantResults.size > 0 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED
                ) {
                    // allow
                } else {
                    //deny
                }
                return
            }
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        ${configuration?.navigationType === "sideBar" ? `
        return if (actionBarDrawerToggle!!.onOptionsItemSelected(item)) {
            true
        } else super.onOptionsItemSelected(item)
        ` : `
        when (item.itemId) {
            android.R.id.home -> {
                // Navigate back to the previous fragment when the back arrow is clicked
                onBackPressed()
                return true
            }
            else -> return super.onOptionsItemSelected(item)
        }
    `}
        
    }

}
  `;
};
