package com.qimai.log

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import com.qimai.log.service.ScheduledExecutionService
import com.tencent.mars.xlog.Log
import com.tencent.mars.xlog.Xlog

class LogInit private constructor() {
    private lateinit var mLogConfig: QmLogConfig

    @JvmOverloads
    fun init(application: Context) {
        init(QmLogConfig(application))
    }

    @JvmOverloads
    fun init(
        config: QmLogConfig
    ) {
        this.mLogConfig = config
        //addObserver(config.app)
        System.loadLibrary("c++_shared")
        System.loadLibrary("marsxlog")
        var logPath = ""
        if (BuildConfig.DEBUG) {
            logPath = config.logDebugPath
        } else {
            logPath = config.logReleasePath
        }
        val logConfig = Xlog.XLogConfig()
        logConfig.mode = Xlog.AppednerModeAsync
        logConfig.logdir = logPath
        logConfig.nameprefix = "log"
        logConfig.pubkey = ""
        logConfig.compressmode = Xlog.ZLIB_MODE
        logConfig.compresslevel = 0
        logConfig.cachedays = 3
        logConfig.cachedir = ""
        //   if (BuildConfig.DEBUG) {
        logConfig.level = Xlog.LEVEL_DEBUG
        Xlog.setConsoleLogOpen(true)
        //   } else {
        // logConfig.level = Xlog.LEVEL_ALL
        //  Xlog.setConsoleLogOpen(true)
        //}
        Xlog.appenderOpen(logConfig)
        Log.setLogImp(Xlog())
        //检查是否有过期的通知数据
        // val intent = Intent(getConfig().app, ScheduledExecutionService::class.java)
        //  getConfig().app.startService(intent)


    }


    private fun addObserver(mApplication: Context) {

        if (mApplication is Application) {
            mApplication.registerActivityLifecycleCallbacks(object :
                Application.ActivityLifecycleCallbacks {
                override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {

                }

                override fun onActivityStarted(activity: Activity) {
                }

                override fun onActivityResumed(activity: Activity) {
                }

                override fun onActivityPaused(activity: Activity) {
                }

                override fun onActivityStopped(activity: Activity) {
                }

                override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
                }

                override fun onActivityDestroyed(activity: Activity) {
                    Log.appenderClose()
                    Log.appenderFlush(false)
                }

            })

        }
    }

    companion object {
        private val mInstance: LogInit = LogInit()
        fun getInstance(): LogInit {
            return mInstance
        }
    }

    fun getConfig() = mLogConfig

}