package com.castlabs.sdk.analytics_demo.utils

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class APIService(private var call: Call<String>) {

	var result: String? = null
	var error: String? = null
	private var successListener: (() -> Unit)? = null
	private var errorListener: (() -> Unit)? = null

	companion object {
		val apiInterface: APIInterface = APIClient.getClient().create(APIInterface::class.java)
	}

	fun start() {
		call.enqueue(object : Callback<String> {
			override fun onResponse(call: Call<String>, response: Response<String>) {
				result = response.body()
				if (result == null) {
					error = response.code().toString()
					errorListener?.invoke()
				}
				else {
					successListener?.invoke()
				}
			}
			override fun onFailure(call: Call<String>, t: Throwable) {
				error = t.message
				errorListener?.invoke()
			}
		})
	}

	fun onSuccess(listener: (() -> Unit)): APIService {
		this.successListener = listener
		return this
	}

	fun onError(listener: (() -> Unit)): APIService {
		this.errorListener = listener
		return this
	}
}
