package com.tt.honeyDue.widget

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.tt.honeyDue.data.DataManager
import com.tt.honeyDue.models.TaskCompletionCreateRequest
import com.tt.honeyDue.network.APILayer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * BroadcastReceiver for handling task actions from widgets
 */
class WidgetTaskActionReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        when (intent.action) {
            "com.tt.honeyDue.COMPLETE_TASK" -> {
                val taskId = intent.getIntExtra("task_id", -1)
                if (taskId != -1) {
                    completeTask(context, taskId)
                }
            }
        }
    }

    private fun completeTask(context: Context, taskId: Int) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                // Check if user is authenticated
                val token = DataManager.authToken.value
                if (token.isNullOrEmpty()) {
                    return@launch
                }

                // Create completion request
                val request = TaskCompletionCreateRequest(
                    taskId = taskId,
                    notes = "Completed from widget"
                )

                // Complete the task via API
                val result = APILayer.createTaskCompletion(request)

                // Update widgets after completion
                if (result is com.tt.honeyDue.network.ApiResult.Success) {
                    WidgetUpdateManager.updateAllWidgets(context)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}
