package fr.salaun.tristan.jsontest

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonParser
import com.google.gson.reflect.TypeToken
import java.lang.reflect.Type

class MainActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "MainActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var list = arrayListOf(
                Book(
                        id = "01fsEF", name = "1984",
                        author = "George Orwell",
                        genre = "Fiction dystopique",
                        numpages = 376,
                        releaseDate = "1949",
                        cover = "1984.png"
                ),
                Book(
                        id = "3H1J0n",
                        name = "Le Meilleur des mondes",
                        author = "Aldous Huxley",
                        genre = "Science-fiction",
                        numpages = 285,
                        releaseDate = "1932",
                        cover = "meilleur-des-mondes.jpg"
                ),
                Book(
                        id = "MbtsI7",
                        name = "Malevil",
                        author = "Robert Merle",
                        genre = "Littératures de l'imaginaire",
                        numpages = 541,
                        releaseDate = "1972",
                        cover = "malevil.jpg"
                )
        )

        var bookList = BookList(list)

        // Serialization
        val gson = Gson()
        val listType: Type = object : TypeToken<BookList?>() {}.type
        val jsonResult: String = gson.toJson(bookList, listType)
        Log.d(TAG, "onCreate jsonResult = $jsonResult")

        Log.d(TAG, "onCreate jsonResult = ${jsonToPrettyFormat(jsonResult)}")

        // Deserialization
        val bookList2: BookList = Gson().fromJson(jsonResult, listType)
        Log.d(TAG, "onCreate bookList2 = ${bookList2}")
    }

    fun jsonToPrettyFormat(jsonString: String?): String? {
        val json = JsonParser.parseString(jsonString).asJsonObject
        val gson = GsonBuilder()
                .serializeNulls()
                .disableHtmlEscaping()
                .setPrettyPrinting()
                .create()
        return gson.toJson(json)
    }
}
