package com.mogo.cloud.network

import com.mogo.cloud.network.listener.OkHttpEventListener
import okhttp3.Call
import okhttp3.EventListener.Factory
import okhttp3.Protocol
import okhttp3.Response
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Proxy

class WeakNetworkEventFactory {
    companion object {
        val FACTORY by lazy {
            Factory { WeakNetworkEventListener() }
        }

        private var listener: OnHttpRttListener? = null

        internal fun setListener(httpRttListener: OnHttpRttListener?) {
            listener = httpRttListener
        }
    }

    /**
     * 弱网络事件监听器
     */
    private class WeakNetworkEventListener : OkHttpEventListener() {

        private var timeStamp: Long = 0

        override fun callStart(call: Call) {
            super.callStart(call)
            timeStamp = System.currentTimeMillis()
        }

        override fun connectFailed(
            call: Call,
            inetSocketAddress: InetSocketAddress,
            proxy: Proxy,
            protocol: Protocol?,
            ioe: IOException
        ) {
            super.connectFailed(call, inetSocketAddress, proxy, protocol, ioe)
            listener?.onFailEvent(
                this.hashCode(),
                call.request().url().toString(),
                System.currentTimeMillis() - timeStamp
            )
        }

        override fun responseHeadersEnd(call: Call, response: Response) {
            super.responseHeadersEnd(call, response)
            listener?.onHttpRttReceived(
                this.hashCode(),
                call.request().url().toString(),
                System.currentTimeMillis() - timeStamp
            )
        }

        override fun logMethod(name: String, startTime: Long) {
            super.logMethod(name, startTime)
            val time = System.nanoTime() - startTime
            // 对超出4秒的网络请求打印日志
            if (time > 4000000000) {
                listener?.logMethod(name, startTime)
            }
        }

    }

    internal interface OnHttpRttListener {
        fun onHttpRttReceived(hashCode: Int, url: String, timeStamp: Long)

        fun onFailEvent(hashCode: Int, url: String, timeStamp: Long)

        fun logMethod(name: String, startTime: Long)
    }
}