package hr.algebra.nasa.api

import android.content.Context
import android.content.Intent
import android.util.Log
import hr.algebra.nasa.HostActivity
import hr.algebra.nasa.NasaReceiver
import hr.algebra.nasa.framework.sendBroadcast
import hr.algebra.nasa.handler.download
import hr.algebra.nasa.model.Item
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create
import java.io.File
import java.net.HttpURLConnection
import java.net.URL

class NasaFetcher(private val context: Context) {

    private val nasaApi: NasaApi
    init {
        val retrofit = Retrofit.Builder()
            .baseUrl(API_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        nasaApi = retrofit.create<NasaApi>()
    }

    fun fetchItems(count: Int = 10) {
        val request = nasaApi.fetchItems()

        request.enqueue(object: Callback<Record> {
            override fun onResponse(
                call: Call<Record?>,
                response: Response<Record?>
            ) {
                response.body()?.record.let { populateItems(it) }
            }

            override fun onFailure(
                call: Call<Record?>,
                t: Throwable
            ) {
                Log.e("ERROR", t.toString(), t)
            }
        })

    }

    private fun populateItems(nasaItems: List<NasaItem>?) {
        val items = mutableListOf<Item>()
        val scope = CoroutineScope(Dispatchers.IO)
        scope.launch {
            nasaItems?.forEach {
                val picturePath = download(context, it.url)
                items.add(
                    Item(
                        null,
                        it.title,
                        it.explanation,
                        picturePath ?: "",
                        it.date,
                        false
                    )
                )
            }
            // back to the FG
            context.sendBroadcast<NasaReceiver>()
        }
    }

}