package it.danieleverducci.openweddingapp.networking

import android.content.Context
import android.util.Log
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.VolleyError
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import it.danieleverducci.openweddingapp.entities.Jsonable
import it.danieleverducci.openweddingapp.entities.NtfyMessage
import org.json.JSONObject

/**
 * See Ntfy https://ntfy.sh/docs
 */
class NtfySubscriptionNet (val context: Context) {
    companion object {
        val TAG = "NtfySubscriptionNet"
    }

    val queue: RequestQueue

    init {
        queue = Volley.newRequestQueue(context)
    }

    fun getItems(url: String, listener: OnItemsObtainedListener) {
        val request = StringRequest(
            Request.Method.GET,
            url,
            {
                val items = ArrayList<NtfyMessage>()
                // Ntfy returns a multi-line string
                // Every line is a JSONObject
                for (line in it.split("\n")) {
                    if (line.trim().isNotEmpty()) {
                        val jo = JSONObject(line)
                        val item = NtfyMessage(jo)
                        items.add(item)
                    }
                }
                listener.OnItemsObtained(items)
            },
            {
                listener.OnError(it)
            })
        queue.add(request)
    }

    interface OnItemsObtainedListener {
        fun OnItemsObtained(items: List<NtfyMessage>)
        fun OnError(error: VolleyError)
    }

}