/*
 * ********************************************************************************************************************
 *                     :*$@@%$*:                         ;:                ;;    ;;
 *                   :@@%!  :!@@%:                       %!             ;%%@@%$ =@@@@@@@%;     @%@@@%%%%@@@@@
 *                  :@%;       :$=                       %%$$$%$$         ;$$  ;$@=   !@$
 *                  =@!                                  %!              @ $=;%   !@@@%:      !$$$$$$$$$$$$$$=
 *                  =@*                                  %!              @ $= % %@=   =%@!      %=
 *             *$%%! @@=        ;=$%%%$*:                %!              @ $= % =%%%%%%@$      *%:         =%
 *           %@@!:    !@@@%=$@@@@%!  :*@@$:              %!              @ $= % $*     ;@      @*          :%*
 *         ;@@!          ;!!!;:         ;@%:      =======@%========*     @ $$ % $%*****$@     :@$=*********=@$
 *         $@*   ;@@@%=!:                *@*
 *         =@$    ;;;!=%@@@@=!           =@!
 *          %@$:      =@%: :*@@@*       %@=                    Copyright (c) 2016-2018.  北京上格云技术有限公司
 *           ;%@@$=$@@%*       *@@@$=%@@%;
 *              ::;::             ::;::                                              All rights reservad.
 * ********************************************************************************************************************
 */

package cn.sagacloud.cadengine


import com.google.gson.FieldNamingPolicy
import com.sybotan.base.extensions.toJson
import okhttp3.*
import com.sybotan.base.utils.SJsonUtil
import java.io.File
import java.util.concurrent.TimeUnit


/**
 * Created by mengxy on 2018/10/16.
 * 创建日期：2018/10/16on ${time}
 * 描述：
 * 作者：zwx
 */
object OkhttpUtil {

    /** http客户端 */
    private val httpClient: OkHttpClient by lazy {
        val client = OkHttpClient().newBuilder()
                .readTimeout(600, TimeUnit.SECONDS)
                .writeTimeout(600 , TimeUnit.SECONDS)
                .connectTimeout(600 , TimeUnit.SECONDS)
//                .cache(cache)
                .build()
        client
    }

    /** 缓存 路径 */
    private val cacheFile = File(MyApplication.getContext().cacheDir, "cache")
    /**  缓存时间*/
    private val cache = Cache(cacheFile, (1024 * 1024 * 100).toLong()) //100Mb
    private val JSON = MediaType.parse("application/json; charset=utf-8")

    /**
     * post请求 json
     *
     * 不能私有
     */
    fun postRequestJson(url: String, json: String): String {
        val jsonBody = FormBody.create(JSON, json)
        val request = Request.Builder()
                .url(url)
                .post(jsonBody)
                .build()
        val call = httpClient.newCall(request)
        try {
            val response = call.execute()
            response.code()
            if (response.isSuccessful) {
//                LogUtils.e("请求成功code${response.code()},url=${url}")
            } else {
//                LogUtils.e("请求成功code${response.code()},url=${url}")
            }
            return response.body()!!.string()
        } catch (e: Throwable) {
            e.printStackTrace()
            return ""
        }
        return ""
    } // Function postRequest()





    /**
     * post 对象
     */
    inline fun <reified T> postObj(url: String, requestBody: Any, namingPolicy: FieldNamingPolicy? = null): T {
        val responseJson = postRequestJson(url, requestBody.toJson())
//        LogUtils.e("数据 :${ responseJson.toJson()}")
        return SJsonUtil.fromJson<T>(responseJson)
    } // Function postObj()

    /**
     * get 对象
     */
    inline fun <reified T> getObj(url: String, namingPolicy: FieldNamingPolicy? = null): T {
        val responseJson = getRequest(url)
        return SJsonUtil.fromJson(responseJson)
    } // Function postObj()



    /**
     *  get 请求
     */
    fun getRequest(url: String): String {
        val request = Request.Builder()
                .url(url)
                .get()
                .build()
        val call = httpClient.newCall(request)
        try {
            val response = call.execute()
            if (response.isSuccessful) {
//                LogUtils.e("请求成功code${response.code()},url=${url}")
            } else {
//                LogUtils.e("请求失败code${response.code()},url=${url}")
            }
            return response.body()!!.string()
        } catch (e: Throwable) {
            e.printStackTrace()
        }
        return ""
    }

    /**
     *  get 请求
     */
    fun getRequest(url: String,projectId: String): String {
        val request = Request.Builder()
                .url(url)
                .addHeader("ProjectId",projectId)
                .get()
                .build()
        val call = httpClient.newCall(request)
        try {
            val response = call.execute()
            if (response.isSuccessful) {
//                LogUtils.e("请求成功code${response.code()},url=${url}")
            } else {
//                LogUtils.e("请求失败code${response.code()},url=${url}")
            }
            return response.body()!!.string()
        } catch (e: Throwable) {
            e.printStackTrace()
        }
        return ""
    }

    //http://prod-data.oss-cn-beijing.aliyuncs.com/test%2Ffiles%2Frevit%2FFl110108000327d8f006c39f49feb40e24a7ef22323220181119025802bim.jsonz?OSSAccessKeyId=LTAIHLlfCwmMRbV4&Expires=1542614466&Signature=RqDeGJn2DvnoqQOoUdQAyihvf1A%3D


    /**
     * 下载图形文件Gzip
     */
    fun getGzipMap(url: String): String {
        try {
            var isGzip = false
            val request = Request.Builder()
                    .url(url)
                    .get()
                    .header("Accept-Encoding", "gzip")
                    .build()
            val call = httpClient.newCall(request)

            val response = call.execute()
            if (response.isSuccessful) {
//                LogUtils.e("请求成功code${response.code()},url=${url}")
            } else {
//                LogUtils.e("请求失败code${response.code()},url=${url}")
            }
            return  GzipUtil.uncompressToString(response.body()!!.bytes())
        } catch (e: Exception) {
            e.printStackTrace()
            return ""
        }
        return ""

    }



}