package com.develop.food.base.utils

import android.util.Log
import com.develop.base.BuildConfig
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import java.util.regex.Matcher
import java.util.regex.Pattern

class LogRequestUtil {
    companion object {

        // 输出http请求日志
        fun logHttpResponse(request: Request, response: Response) {
            if (!BuildConfig.DEBUG) {
                return
            }
            val builder = StringBuilder()
            builder.append("\n method:").append(request.method)
            builder.append("\n host:").append(request.url.host)
            builder.append("\n path:").append(request.url.encodedPath)
            builder.append("\n Content-Type:").append(request.header("Content-Type"))
            builder.append("\n X-Source:").append(request.header("X-Source"))
            builder.append("\n X-Signature:").append(request.header("X-Signature"))

            builder.append("\n query:").append(request.url.query)
            if (request.body != null) {
                val bodyMsg = bodyPreview(request)
                builder.append("\n body:").append(
                    bodyMsg
                )
            }
            //以下是response的内容
            builder.append("\n status:").append(response.code.toString())
            builder.append("\n response:").append(
                bodyPreview(
                    response
                )
            )
            val headerSessionId = "x-sessionid"
            val sessionId = response.header(headerSessionId)
            if (sessionId != null) {
                builder.append("\n x-sessionid:").append(sessionId)
            }
            longLog("ApiResponseTag", builder.toString())
        }

        private fun bodyPreview(response: Response): String? {
            if (response.body != null) {
                try {
                    return response.peekBody((1024 * 1024).toLong()).string()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            return null
        }

        private fun bodyPreview(request: Request): String? {
            if (request.body != null) {
                try {
                    val buffer = Buffer()
                    request.body!!.writeTo(buffer)
                    return buffer.readUtf8()
                } catch (e: Exception) {
                    e.printStackTrace()
                }

            }
            return null
        }

        /**
         * 截断输出日志
         * @param msgString
         */
        private fun longLog(tag: String?, msgString: String?) {
            if (msgString?.contains("�") == true){
                return
            }
            var msg = msgString
            if (tag == null || tag.isEmpty() || msg == null || msg.isEmpty()
            ) return
            val segmentSize = 3 * 1024
            val length = msg.length.toLong()
            // 长度小于等于限制直接打印
            if (length <= segmentSize) {
                Log.d(tag, msg)
            } else { // 循环分段打印日志
                while (msg!!.length > segmentSize) {
                    val logContent = msg.substring(0, segmentSize)
                    msg = msg.replace(logContent, "")
                    Log.d(tag, logContent)
                }
                // 打印剩余日志
                Log.d(tag, msg)
            }
        }

        private fun isMessyCode(strName: String): Boolean {
            try {
                val p: Pattern = Pattern.compile("\\s*|\t*|\r*|\n*")
                val m: Matcher = p.matcher(strName)
                val after: String = m.replaceAll("")
                val temp = after.replace("\\p{P}".toRegex(), "")
                val ch = temp.trim { it <= ' ' }.toCharArray()
                val length = ch.size
                for (i in 0 until length) {
                    val c = ch[i]
                    if (!Character.isLetterOrDigit(c)) {
                        val str = "" + ch[i]
                        if (!str.matches(Regex("[\u4e00-\u9fa5]+"))) {
                            return true
                        }
                    }
                }
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
            return false
        }
    }


}