package com.guadou.lib_baselib.core

import android.app.Application
import android.graphics.Color
import android.os.Environment
import android.os.Handler
import com.guadou.basiclib.BuildConfig
import com.guadou.basiclib.R
import com.guadou.lib_baselib.receiver.ConnectivityReceiver
import com.guadou.lib_baselib.utils.CommUtils
import com.guadou.lib_baselib.utils.ThreadPoolUtils
import com.guadou.lib_baselib.utils.log.YYLogUtils
import com.guadou.lib_baselib.utils.log.interceptor.Log2FileInterceptor
import com.guadou.lib_baselib.utils.log.interceptor.LogDecorateInterceptor
import com.guadou.lib_baselib.utils.log.interceptor.LogPrintInterceptor
import com.guadou.lib_baselib.view.gloading.Gloading
import com.guadou.lib_baselib.view.gloading.GloadingRoatingAdapter
import com.guadou.lib_baselib.view.titlebar.EasyTitleBar
import com.hjq.toast.ToastUtils
import java.io.File

/**
 * 底层的模组依赖库都在这里初始化
 * 当前类在Application中初始化
 */
object BaseLibCore {
    /**
     * 初始化全局工具类和图片加载引擎
     */
    fun init(application: Application, handler: Handler?, mainThread: Int) {

        //CommUtil初始化
        CommUtils.init(application, handler, mainThread)

        //初始化全局通用的线程池
        ThreadPoolUtils.init()

        //EaseTitleBar的初始化
        EasyTitleBar.init()
            .backIconRes(R.mipmap.iv_blue_back)
            .backgroud(Color.WHITE)
            .titleSize(18)
            .showLine(true)
            .lineHeight(1)
            .menuImgSize(23)
            .menuTextSize(16)
            .lineColor(application.applicationContext.resources.getColor(R.color.divider_color))
            .titleColor(Color.BLACK)
            .viewPadding(10)
            .titleBarHeight(46)

        //全局的Loading状态默认配置
        Gloading.initDefault(GloadingRoatingAdapter())

        //吐司框架初始化
        ToastUtils.init(application)


        //配置Log的拦截器，只有Debug下才生效
        YYLogUtils.addInterceptor(LogDecorateInterceptor(BuildConfig.DEBUG))
        YYLogUtils.addInterceptor(LogPrintInterceptor(BuildConfig.DEBUG))

        val logPath = if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED)
            application.applicationContext.getExternalFilesDir("log")?.absolutePath
                ?: application.applicationContext.filesDir.absolutePath + "/log/"
        else application.applicationContext.filesDir.absolutePath + "/log/"

        val dir = File(logPath)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        YYLogUtils.addInterceptor(Log2FileInterceptor.getInstance(logPath, BuildConfig.DEBUG))

    }

    /**
     * 注册网络监听
     */
    fun registerNetworkObserver(application: Application?) {
        ConnectivityReceiver.registerReceiver(application!!)
    }

    fun unregisterNetworkObserver(application: Application?) {
        ConnectivityReceiver.unregisterReceiver(application!!)
    }
}