package com.example.modifier

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.Toast
import androidx.core.content.ContextCompat
import com.example.modifier.data.AppDatabase
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

class MyReceiver : BroadcastReceiver() {

    private val TAG = "MyReceiver"

    override fun onReceive(context: Context, intent: Intent) {
        when (intent.action) {
            "clear_backup" -> {
                Toast.makeText(context, "Clearing backup", Toast.LENGTH_SHORT).show()
                CoroutineScope(Dispatchers.IO).launch {
                    clearBackup(context)
                }
            }
        }
    }

    private suspend fun clearBackup(context: Context) {
        val dao = AppDatabase.getDatabase(context).itemDao()
        dao.getAll().forEach {
            Log.i(TAG, "Deleting ${it.id}: ${it.path}")
            File(it.path).deleteRecursively()
            dao.delete(it)
        }
        ContextCompat.getExternalFilesDirs(context, "backup")[0].listFiles()?.forEach {
            Log.i(TAG, "clearBackup: Deleting ${it.absolutePath}")
            shellRun("rm -rf ${it.absolutePath}")
        }
    }
}