summaryrefslogtreecommitdiff
path: root/app/src/main/java/dev/equestria/delta/HTTPRequest.kt
blob: 1bebbc0f19a73774babb04ad79178522953036d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package dev.equestria.delta

import android.content.Context
import android.content.res.Resources
import android.util.Log
import com.android.volley.Request
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import dev.equestria.delta.databinding.ActivityMainBinding
import org.json.JSONObject
import kotlin.system.exitProcess

class HTTPRequest {
    companion object {
        fun request(
            url: String,
            session: String?,
            context: Context,
            resources: Resources,
            activity: MainActivity,
            initial: Boolean,
            binding: ActivityMainBinding,
            positiveCallback: (JSONObject) -> Unit = { },
            negativeCallback: (Unit) -> Unit = { }
        ) {
            val volleyQueue = Volley.newRequestQueue(context)

            val data = JSONObject()
            data.put("session", session)

            val jsonObjectRequest = JsonObjectRequest(Request.Method.POST, url, data,

                { response ->
                    Log.i("HTTPRequest", response.toString())
                    positiveCallback(response)
                },

                { error ->
                    MaterialAlertDialogBuilder(context).setCancelable(false)
                        .setTitle(resources.getString(R.string.offline_title))
                        .setMessage(resources.getString(R.string.offline_message))
                        .setPositiveButton(resources.getString(R.string.offline_retry)) { _, _ ->
                            if (initial) {
                                activity.initialCheck()
                            } else {
                                binding.webView.reload()
                            }
                        }.setNegativeButton(resources.getString(R.string.offline_close)) { _, _ ->
                            activity.moveTaskToBack(true)
                            exitProcess(0)
                        }.setNeutralButton(resources.getString(R.string.offline_status)) { _, _ ->
                            negativeCallback(Unit)
                        }.show()
                    Log.e("HTTPRequest", "Request error: ${error.localizedMessage}")
                })

            volleyQueue.add(jsonObjectRequest)
        }
    }
}