package it.danieleverducci.openweddingapp.networking

import android.content.Context
import android.os.Handler
import android.util.Log
import com.android.volley.DefaultRetryPolicy
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import it.danieleverducci.openweddingapp.Config
import it.danieleverducci.openweddingapp.entities.GalleryItem
import it.danieleverducci.openweddingapp.entities.Token
import org.json.JSONObject
import java.io.File


class TokenNet(val context: Context) {
    companion object {
        val TAG = "TokenNet"
        val TIMEOUT = 10*1000
    }

    enum class Error {
        USER_NOT_FOUND, OTHER
    }

    val queue: RequestQueue

    init {
        queue = Volley.newRequestQueue(context)
    }

    fun postItem(listener: OnTokenPostCompletedListener, code: String) {
        val jo = JSONObject()
        jo.put("code", code)
        val request = JsonObjectRequest(
            Request.Method.POST,
            "${Config.API_BASE_URL}${Config.API_ENDPOINT_TOKEN}/create.php",
            jo,
            Response.Listener<JSONObject> {
                listener.OnTokenPostCompleted(Token(it), null)
            },
            Response.ErrorListener {
                Log.e(TAG, "Unable to obtain token: ${it.message}")
                if (it.networkResponse?.statusCode == 404) {
                    listener.OnTokenPostCompleted(null, Error.USER_NOT_FOUND)
                } else {
                    listener.OnTokenPostCompleted(null, Error.OTHER)
                }
            }
        )
        // Change default timeout to 10s, as the login has an anti-bruteforce delay of 5 secs
        request.setRetryPolicy(
            DefaultRetryPolicy(
                TIMEOUT,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)
        )
        // Enqueue request
        queue.add(request)
    }

    interface OnTokenPostCompletedListener {
        fun OnTokenPostCompleted(item: Token?, error: Error?)
    }

}