package com.example.wallisyn.tool

import android.Manifest
import android.app.Activity
import android.content.ContentValues
import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.util.Log
import androidx.core.app.ActivityCompat
import com.example.wallisyn.MyApp
import com.example.wallisyn.mybean.MyData
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.json.JSONArray
import org.json.JSONObject
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

object JsonData {


    fun getData(jsonStr: String, category: String): MutableList<MyData> {
        val jsonArray = JSONArray(jsonStr)
        var data = mutableListOf<MyData>()

        var get: JSONObject
        var text_description: String

        var links: JSONObject
        var download: String

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


        var users: JSONObject
        var name: String
        var header_large: String
        var user_html: String
        val host = "https://unsplash.com/photos/"

        var bean: MyData
        var indexOf: Int
        var substring: String


        for (i in 0 until 300) {
            get = jsonArray.getJSONObject(i)
            text_description = get.getString("alt_description")
            links = get.getJSONObject("links")
            download = links.getString("download")
//            val downloadLocation = links.getString("download_location")
//            val html = links.getString("html")


            urls = get.getJSONObject("urls")
//            val full = urls.getString("full")
//            val raw = urls.getString("raw")
            regular = urls.getString("regular")
            small = urls.getString("small")
            thumb = urls.getString("thumb")


            users = get.getJSONObject("user")
//            val portfolio_url = users.getString("portfolio_url")
            name = users.getString("name")
            header_large = users.getString("header_large")
//            val header_medium = users.getString("header_medium")
//            val header_small = users.getString("header_small")
            user_html = users.getString("authorHtml")


            indexOf = download.indexOf("/download")
            substring = download.substring(host.length, indexOf)
//            Log.d(MyApp.TAG, "i=$i----------substring=$substring")

            bean = MyData().apply {
                imId = substring
                categoryName = category
                description = text_description
                fullUrl = download
                previewUrl1080 = regular
                previewUrl400 = small
                previewUrl200 = thumb
                authorName = name
                authorHeader = header_large
                authorHtml = user_html
            }
            data.add(bean)
        }


        return data
    }


    fun downloadFile(
        url: String,
        savePath: String,
        result: (Boolean, input: InputStream?) -> Unit
    ): Call {
        var client = OkHttpClient()
        var request = Request.Builder().url(url).build()
        var call = client.newCall(request)
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                result.invoke(false, null)
            }

            override fun onResponse(call: Call, response: Response) {
                response.body?.run {
                    val byteStream = byteStream()
                    val writeFile = writeFile(byteStream, savePath)
                    result.invoke(writeFile, byteStream)
                } ?: run {
                    result.invoke(false, null)
                }
            }
        })
        return call
    }

    fun writeFile(input: InputStream, filePath: String): Boolean {
        try {
            val byte = ByteArray(4096)
            val output = ByteArrayOutputStream()
            var l: Int
            while (input.read(byte).also { l = it } != -1) {
                output.write(byte, 0, l)
            }
            val fileDe = File(filePath)
            if (!fileDe.exists()) {
                fileDe.createNewFile()
            }
            val fileOutputStream = FileOutputStream(filePath)
            fileOutputStream.write(output.toByteArray())
            output.close()
            fileOutputStream.close()
            return true
        } catch (ex: Exception) {
            Log.d("-----------", "---------ex=" + ex.message)
            return false
        }


    }


    fun saveToGallery(context: Context, photoFile: File): Uri? {
        val displayName = "${System.currentTimeMillis()}.jpg"
        val contentValues = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, displayName)
            put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                put(MediaStore.Images.Media.IS_PENDING, 1)
            }
        }

        val contentResolver = context.contentResolver
        val collectionUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
        } else {
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        }

        val imageUri = contentResolver.insert(collectionUri, contentValues)

        imageUri?.let { uri ->
            try {
                contentResolver.openOutputStream(uri)?.use { outputStream ->
                    val inputStream = FileInputStream(photoFile)
                    inputStream.copyTo(outputStream)
                    inputStream.close()
                    outputStream.close()
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    contentValues.clear()
                    contentValues.put(MediaStore.Images.Media.IS_PENDING, 0)
                    contentResolver.update(uri, contentValues, null, null)
                } else {

                }
                return uri
            } catch (e: IOException) {
                Log.d(MyApp.TAG, "-----------------e=${e.printStackTrace()}")
                return null
            }
        } ?: run {
            Log.d(MyApp.TAG, "----------------false")
            return null
        }
    }


    fun requestPermission(context: Activity, requestCode: Int): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            return true
        }
        return if (context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                context,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                requestCode
            )
            false
        } else {
            true
        }
    }

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


}