summaryrefslogtreecommitdiffstats
path: root/app/src/main/java/com/example/alcagotchi/AlcoGotchi.kt
diff options
context:
space:
mode:
authorLeonardo Bishop <me@leonardobishop.com>2024-11-17 00:11:08 +0000
committerLeonardo Bishop <me@leonardobishop.com>2024-11-17 00:11:17 +0000
commit25a3947a1dc4233b43b2e4e8e79b127fa7dc57f7 (patch)
treec19258e9d8d2d4edbb604ee18ca0895c049aae10 /app/src/main/java/com/example/alcagotchi/AlcoGotchi.kt
parenta0fd80340f93b04eba585254dc2a718770a30e92 (diff)
genting
Diffstat (limited to 'app/src/main/java/com/example/alcagotchi/AlcoGotchi.kt')
-rw-r--r--app/src/main/java/com/example/alcagotchi/AlcoGotchi.kt72
1 files changed, 70 insertions, 2 deletions
diff --git a/app/src/main/java/com/example/alcagotchi/AlcoGotchi.kt b/app/src/main/java/com/example/alcagotchi/AlcoGotchi.kt
index d1c5d7a..bbc5a5b 100644
--- a/app/src/main/java/com/example/alcagotchi/AlcoGotchi.kt
+++ b/app/src/main/java/com/example/alcagotchi/AlcoGotchi.kt
@@ -1,5 +1,73 @@
package com.example.alcagotchi
-class AlcoGotchi {
+import okhttp3.Call
+import okhttp3.Callback
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+import okhttp3.Response
+import org.json.JSONObject
+import java.io.IOException
+
+class AlcoGotchi private constructor() {
+
+ private val client = OkHttpClient()
+ private val jsonMediaType = "application/json; charset=utf-8".toMediaType()
+
+ var baseUrl = "http://192.168.4.1:80"
var coins = 100
-} \ No newline at end of file
+
+ companion object {
+ @Volatile private var instance: AlcoGotchi? = null
+
+ fun getInstance() =
+ instance ?: synchronized(this) {
+ instance ?: AlcoGotchi().also { instance = it }
+ }
+ }
+
+ private fun buildUrl(path: String): String {
+ return "$baseUrl/$path"
+ }
+
+ val basicCallback = object : Callback {
+ override fun onFailure(call: Call, e: IOException) {
+ e.printStackTrace()
+ }
+
+ override fun onResponse(call: Call, response: Response) {
+ response.use {
+ handleStateResponse(response)
+ }
+ }
+ }
+
+ fun handleStateResponse(response: Response) {
+ if (!response.isSuccessful) throw IOException("Unexpected code $response")
+
+ val json = JSONObject(response.body!!.string())
+
+ coins = json.getJSONObject("data").getInt("alco_coin")
+ }
+
+ fun getState() {
+ val request = Request.Builder()
+ .url(buildUrl(""))
+ .build()
+
+ client.newCall(request).enqueue(basicCallback)
+ }
+
+ fun postGamble(amount: Int) {
+ val body = JSONObject()
+ body.put("bet", amount)
+
+ val request = Request.Builder()
+ .url(buildUrl("gamble"))
+ .post(body.toString().toRequestBody(jsonMediaType))
+ .build()
+
+ client.newCall(request).enqueue(basicCallback)
+ }
+}