package com.mints.goodmoney

import android.app.IntentService
import android.app.Notification
import android.content.Context
import android.content.Intent
import cn.jpush.android.api.BasicPushNotificationBuilder
import cn.jpush.android.api.JPushInterface
import com.mints.goodmoney.manager.BxmManager.initBxm
import com.mints.goodmoney.manager.LiebaoManager
import com.mints.goodmoney.manager.ShumeiManager
import com.mints.goodmoney.manager.ZhangyueManager
import com.mints.library.utils.CommonUtils
import com.mob.MobSDK
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.FormatStrategy
import com.orhanobut.logger.Logger
import com.orhanobut.logger.PrettyFormatStrategy
import com.tendcloud.tenddata.TCAgent
import com.umeng.commonsdk.UMConfigure

/**
 * 子线程初始化SDK
 */
class InitAppService : IntentService("InitializeService") {

    companion object {
        const val ACTION_INIT = "initApplication"
        var IS_DEBUG = BuildConfig.LOG_DEBUG

        /**
         * 开启intentService
         */
        fun start(context: Context) {
            try {
                val intent = Intent(context, InitAppService::class.java)
                intent.action = ACTION_INIT
                context.startService(intent)
            } catch (e: IllegalStateException) {
                e.printStackTrace()
            }
        }
    }

    private var isInit: Boolean = false

    override fun onHandleIntent(intent: Intent?) {
        if (isInit) return

        intent?.let {
            val action = intent.action
            if (ACTION_INIT == action) {

                initApplication()
                isInit = false
            }
        }
    }

    /**
     * 子线程进行初始化SDK操作
     */
    private fun initApplication() {
        // TalkingData数据埋点与错误日志
        TalkingDataConfig()

        // 初始化ShareSDK
        MobSDK.init(this)

        // 友盟初始化
        initUm(this)

        //logger
        initLogger()

        // 数美
        ShumeiManager.getInstance().initShumei()

        // 极光推送
        initJpush()

        // 掌阅书城
        ZhangyueManager.attachBaseContextIreader(this.application)
        ZhangyueManager.onCreateIreader(this.application)

        // 变现猫
        initBxm(this.application)

        // 猎豹游戏初始化
        LiebaoManager.getInstance().initCmGameSdk()
    }

    /**
     * 设置TalkingData
     */
    private fun TalkingDataConfig() {
        TCAgent.LOG_ON = BuildConfig.DEBUG
        val talkingData_id = CommonUtils.getAppMetaData(MintsApplication.getContext(), "TD_KEY")
        val td_channel_id = CommonUtils.getAppMetaData(MintsApplication.getContext(), "CHANNEL_NAME")
        TCAgent.init(this, talkingData_id, td_channel_id)
        TCAgent.setReportUncaughtExceptions(true)
    }

    /**
     * 友盟初始化
     */
    fun initUm(context: Context?) {
        /**
         * 参数4:设备类型，必须参数，传参数为UMConfigure.DEVICE_TYPE_PHONE则表示手机；传参数为UMConfigure.DEVICE_TYPE_BOX则表示盒子；默认为手机。
         * 参数5:Push推送业务的secret，需要集成Push功能时必须传入Push的secret，否则传空。
         */
        UMConfigure.init(context, CommonUtils.getAppMetaData(MintsApplication.getContext(), "UMENG_KEY"), CommonUtils.getAppMetaData(context, "CHANNEL_NAME"), UMConfigure.DEVICE_TYPE_PHONE, "")
        UMConfigure.setLogEnabled(true)
    }

    /**
     * 自定义logger
     */
    private fun initLogger() {
        if (IS_DEBUG) {
            val formatStrategy: FormatStrategy = PrettyFormatStrategy.newBuilder()
                    .showThreadInfo(false) //是否选择显示线程信息，默认为true
                    .methodCount(0) //方法数显示多少行，默认2行
                    .methodOffset(7) //隐藏方法内部调用到偏移量，默认5
                    .tag("mints---network") //自定义TAG全部标签，默认PRETTY_LOGGER
                    .build()
            Logger.addLogAdapter(AndroidLogAdapter(formatStrategy))
        }
    }

    /**
     * 绑定jpush
     */
    private fun initJpush() {
        JPushInterface.setDebugMode(BuildConfig.LOG_DEBUG) // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this)
        val builder = BasicPushNotificationBuilder(applicationContext)
        builder.statusBarDrawable = R.mipmap.ic_launcher
        builder.notificationFlags = Notification.FLAG_AUTO_CANCEL //设置为自动消失
        builder.notificationDefaults = Notification.DEFAULT_SOUND or Notification.DEFAULT_VIBRATE or Notification.DEFAULT_LIGHTS // 设置为铃声与震动都要
        JPushInterface.setDefaultPushNotificationBuilder(builder)
    }
}