aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/java/xyz/adjutor/aniki/manga/topmanga/TopMangaPage.kt
blob: ea240b91c8bd467af33398eaa6f1b4feac5935c7 (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package xyz.adjutor.aniki.manga.topmanga

import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.google.android.material.snackbar.Snackbar
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.R
import java.lang.reflect.Type


class TopMangaPage : Fragment() {

    private lateinit var sharedPreferences: SharedPreferences
    val gson: Gson = GsonBuilder()
        .setLenient()
        .create()
    private var baseUrl = "https://api.jikan.moe/" //the api's base url
    var page: Int = 1

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.top_manga_page, container, false)

        sharedPreferences = view.context.getSharedPreferences("sp_manga", Context.MODE_PRIVATE)

        val mangaList: List<TopManga>? = getDataFromCache()
        if (mangaList != null) {
            showList(view, mangaList)
        } else {
            makeApiCall(view, baseUrl, 1)
        }

        // add other pages when we touch the bottom
        val recyclerView: RecyclerView = view.findViewById(R.id.recycler_view)
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (!recyclerView.canScrollVertically(1)) { //direction integers: -1 for up, 1 for down, 0 will always return false.
                    page += 1
                    makeApiCall(view, baseUrl, page)
                    Snackbar.make(
                        requireView(),
                        "Page $page has been loaded.",
                        Snackbar.LENGTH_LONG
                    )
                        .setAction("Action", null).show()
                }
            }
        })

        return view

    }

    private fun getDataFromCache(): List<TopManga>? {
        //the value of the mangaList json, if nothing is found, return null
        val jsonManga: String? = sharedPreferences.getString("jsonMangaList", null)

        //if it's null, well, return null
        return if (jsonManga == null) {
            null
        } else { //else deserialize the list and return it
            val listType: Type = object : TypeToken<List<TopManga>>() {}.type
            gson.fromJson(jsonManga, listType)
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        //button to return to the home page
        view.findViewById<Button>(R.id.button_home).setOnClickListener {
            findNavController().navigate(R.id.action_TopMangaPage_to_HomePage)
        }
        view.findViewById<Button>(R.id.button_prev).setOnClickListener {
            if (page > 1) {
                page -= 1
                makeApiCall(view, baseUrl, page)
                Snackbar.make(requireView(), "Page $page has been loaded.", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show()
            } else {
                Snackbar.make(requireView(), "You're already page 1.", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show()
            }
        }
        view.findViewById<Button>(R.id.button_next).setOnClickListener {
            page += 1
            makeApiCall(view, baseUrl, page)
            Snackbar.make(requireView(), "Page $page has been loaded.", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show()
        }

        fun updateList() {
            makeApiCall(view, baseUrl, 1)
            Snackbar.make(requireView(), "Data refreshed", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show()
        }

        //refresh when swiping down at the top of the page
        val swipeRefresh: SwipeRefreshLayout = view.findViewById(R.id.swiperefresh)
        swipeRefresh.setOnRefreshListener {
            updateList()
            page = 1
            swipeRefresh.isRefreshing = false
        }

    }

    //display the recyclerview
    fun showList(view: View, mangaList: List<TopManga>) {
        val recyclerView: RecyclerView = view.findViewById(R.id.recycler_view)
        recyclerView.setHasFixedSize(true)
        recyclerView.layoutManager = LinearLayoutManager(view.context)
        recyclerView.adapter = TopMangaAdapter(mangaList)
        (recyclerView.adapter as TopMangaAdapter).notifyDataSetChanged()
    }

    private fun makeApiCall(view: View, BASE_URL: String, page: Int) {

        val retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()

        val service = retrofit.create(TopMangaApi::class.java)
        val call = service.getTopMangaData(page)

        call.enqueue(object : Callback<TopMangaResponse> {
            override fun onResponse(
                call: Call<TopMangaResponse>,
                response: Response<TopMangaResponse>
            ) {
                if (response.isSuccessful && response.body() != null) { //if the code returned is >= 200 and < 300 AND the the body ain't empty

                    val mangaList: List<TopManga> = response.body()!!
                        .getResults() //getting the "top" field containing our list of TopMangas
                    saveList(mangaList)
                    showList(
                        view,
                        mangaList
                    ) //calling the method in charge of displaying on the recyclerview

                } else {
                    showError() //a snackbar
                }
            }

            override fun onFailure(call: Call<TopMangaResponse>, t: Throwable) {
                showError()
            }

        })
    }

    private fun saveList(mangaList: List<TopManga>) {
        val jsonString: String = gson.toJson(mangaList)

        sharedPreferences
            .edit()
            .putString("jsonMangaList", jsonString)
            .apply()
    }

    private fun showError() {
        Snackbar.make(requireView(), "API ERROR", Snackbar.LENGTH_LONG)
            .setAction("Action", null).show()
    }

}