package xyz.adjutor.aniki.presentation.controller.anime import android.content.Context import android.content.SharedPreferences import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.reflect.TypeToken import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import xyz.adjutor.aniki.data.anime.AnimeApi import xyz.adjutor.aniki.presentation.model.anime.AnimeResponse import xyz.adjutor.aniki.presentation.view.anime.DetailTopAnimeActivity import java.lang.reflect.Type class DetailTopAnimeController { private lateinit var sharedPreferences: SharedPreferences lateinit var gson: Gson private lateinit var baseUrl: String //the api's base url lateinit var view: DetailTopAnimeActivity fun onStart(DetailTopAnimeActivity: DetailTopAnimeActivity, animeId: String) { view = DetailTopAnimeActivity baseUrl = "https://api.jikan.moe/" //the api's base url gson = GsonBuilder() .setLenient() .create() sharedPreferences = view.applicationContext.getSharedPreferences("sp_anime", Context.MODE_PRIVATE) val anime: AnimeResponse? = getDataFromCache(animeId) if (anime != null) { view.showDetail(anime) } else { //taking the API's fields I want and displaying them makeApiCall(baseUrl, animeId) } } private fun getDataFromCache(animeId: String): AnimeResponse? { val jsonAnime: String? = sharedPreferences.getString(animeId, null) return if (jsonAnime == null) { null } else { val type: Type = object : TypeToken() {}.type gson.fromJson(jsonAnime, type) } } private fun makeApiCall(BASE_URL: String, animeId: String) { val retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .build() val service = retrofit.create(AnimeApi::class.java) val call = service.getAnimeData(animeId) //based on the id call.enqueue(object : Callback { override fun onResponse( call: Call, response: Response ) { if (response.isSuccessful && response.body() != null) { //if the code returned is >= 200 and < 300 AND the the body ain't empty val anime = response.body() //getting the AnimeResponse fields saveList(anime) view.showDetail(anime!!) } else { view.showError("API ERROR : is not successful") } } override fun onFailure(call: Call, t: Throwable) { view.showError("API ERROR : onFailure") } }) } fun saveList(anime: AnimeResponse?) { val jsonString: String = gson.toJson(anime) sharedPreferences .edit() .putString(anime?.mal_id.toString(), jsonString) .apply() } }