package de.storchp.fdroidbuildstatus

import android.content.Intent
import android.os.Bundle
import android.util.SparseBooleanArray
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.updatePadding
import dagger.hilt.android.AndroidEntryPoint
import de.storchp.fdroidbuildstatus.adapter.db.DbAdapter
import de.storchp.fdroidbuildstatus.databinding.ActivityImportFavouritesBinding
import de.storchp.fdroidbuildstatus.utils.PreferencesService
import de.storchp.fdroidbuildstatus.utils.addInsetsListener
import java.io.BufferedReader
import javax.inject.Inject


const val PACKAGE_NAME_HEADER = "packageName"

@AndroidEntryPoint
class ImportAppsAsFavouritesActivity : AppCompatActivity() {

    @Inject
    lateinit var preferencesService: PreferencesService

    @Inject
    lateinit var dbAdapter: DbAdapter

    private lateinit var binding: ActivityImportFavouritesBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        enableEdgeToEdge()
        super.onCreate(savedInstanceState)
        binding = ActivityImportFavouritesBinding.inflate(
            layoutInflater
        )
        binding.appIdList.addInsetsListener {
            updatePadding(bottom = it.bottom)
        }
        binding.contentImportFavourites.addInsetsListener {
            updatePadding(left = it.left, right = it.right)
        }
        binding.topAppBar.addInsetsListener {
            updatePadding(left = it.left, right = it.right)
        }
        setContentView(binding.root)
        setSupportActionBar(binding.topAppBar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        onNewIntent(intent)

        binding.importButton.setOnClickListener {
            val checked: SparseBooleanArray = binding.appIdList.checkedItemPositions
            var importCount = 0
            for (i in 0 until binding.appIdList.adapter.count) {
                if (checked[i]) {
                    val packageName = binding.appIdList.adapter.getItem(i) as String
                    dbAdapter.saveFavourite(packageName)
                    importCount++
                }
            }
            Toast.makeText(
                baseContext,
                getString(R.string.import_result, importCount),
                Toast.LENGTH_LONG
            )
                .show()
        }

        binding.cbSelectAll.setOnClickListener {
            val checked = binding.cbSelectAll.isChecked
            for (i in 0 until binding.appIdList.adapter.count) {
                binding.appIdList.setItemChecked(i, checked)
            }

        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        intent.clipData?.let {
            val appList = buildList {
                val firstItem = it.getItemAt(0)
                val content: String? =
                    if (firstItem?.text != null) {
                        firstItem.text.toString()
                    } else if (firstItem.uri != null) {
                        contentResolver.openInputStream(firstItem.uri)?.bufferedReader()
                            ?.use(BufferedReader::readText)
                    } else {
                        null
                    }
                if (content != null) {
                    val lines = content.split("\n")
                    val columns = lines[0].split(",")
                    val colIndex = columns.indexOf(PACKAGE_NAME_HEADER)
                    if (colIndex >= 0) {
                        lines.drop(1).forEach { line ->
                            val packageName = line.split(",")[colIndex]
                            if (packageName.isNotEmpty()) {
                                add(packageName)
                            }
                        }
                    }
                }
            }

            binding.appIdList.adapter =
                ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, appList)

            for (i in appList.indices) {
                binding.appIdList.setItemChecked(i, true)
            }
        }

        if (binding.appIdList.adapter == null || binding.appIdList.adapter.isEmpty) {
            Toast.makeText(baseContext, getString(R.string.import_no_data), Toast.LENGTH_LONG)
                .show()
            finish()
        }

    }
}