package com.apps.chillscreen.tool

import android.content.Context
import com.apps.chillscreen.bean.Picture
import org.json.JSONArray
import org.json.JSONObject

object JsonConvert {
    fun getData(dataResource: String, category: String): MutableList<Picture> {
        val jsonArray = JSONArray(dataResource)
        var pictures = mutableListOf<Picture>()

        var eachItem: JSONObject
        var _description: String

        var links: JSONObject
        var download: String

        var urls: JSONObject
        var regular: String
        var small: String
        var thumb: String

        var user: JSONObject
        var name: String
        var headerLarge: String
        var userHtml: String
        val host = "https://unsplash.com/photos/"

        var picture: Picture
        var mid: String

        for (i in 0 until jsonArray.length()) {
            eachItem = jsonArray.getJSONObject(i)
            _description = eachItem.getString("alt_description")
            links = eachItem.getJSONObject("links")
            download = links.getString("download")
            urls = eachItem.getJSONObject("urls")
            regular = urls.getString("regular")
            small = urls.getString("small")
            thumb = urls.getString("thumb")
            user = eachItem.getJSONObject("user")
            name = user.getString("name")
            headerLarge = user.getString("header_large")
            userHtml = user.getString("authorHtml")
            mid = download.substring(host.length, download.indexOf("/download"))

            picture = Picture().apply {
                imId = mid
                categoryName = category
                description = _description
                fullUrl = download
                previewUrl1080 = regular
                previewUrl400 = small
                previewUrl200 = thumb
                authorName = name
                authorHeader = headerLarge
                authorHtml = userHtml
            }
            PictureManager.addPicture(picture)
            pictures.add(picture)
        }

        return pictures

    }
    fun getSaveFilePath(context: Context, imId: String): String {
        return "${context.cacheDir}/${imId}.jpg"
    }
}