package de.storchp.fdroidbuildstatus

import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import dagger.hilt.android.AndroidEntryPoint
import de.storchp.fdroidbuildstatus.adapter.db.DbAdapter
import javax.inject.Inject

@AndroidEntryPoint
class ExportFavoritesActivity : AppCompatActivity() {

    @Inject
    lateinit var dbAdapter: DbAdapter

    private val openCsv = registerForActivityResult(
        ActivityResultContracts.CreateDocument("text/csv")
    ) { result ->
        if (result != null) {
            contentResolver.openOutputStream(result).use { stream ->
                stream?.writer()?.let { writer ->
                    writer.appendLine(PACKAGE_NAME_HEADER)
                    dbAdapter.loadFavourites().keys.forEach {
                        writer.appendLine(it)
                    }
                    writer.flush()
                }
            }
        }
        finish()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        openCsv.launch("fdroid-buildstatus-favorites.csv")
    }


}
