package com.remax.visualnovel.app.initializer.impl

import android.app.Application
import android.content.Context
import android.net.http.HttpResponseCache
import android.os.Environment
import android.text.TextUtils
import com.chad.library.adapter.base.module.LoadMoreModuleConfig
import com.remax.visualnovel.BuildConfig
import com.remax.visualnovel.app.delegate.ToolbarViewDelegate
import com.remax.visualnovel.app.initializer.AppInitializers
import com.remax.visualnovel.app.widget.CustomLoadMoreView
import com.remax.visualnovel.app.widget.LoadMoreFooter
import com.remax.visualnovel.app.widget.RefreshHeader
import com.remax.visualnovel.utils.NotLoggingTree
import com.dylanc.loadingstateview.LoadingStateView
import com.github.boybeak.skbglobal.SoftKeyboardGlobal
import com.github.sahasbhop.apngview.ApngImageLoader
import com.lzf.easyfloat.EasyFloat
import com.pengxr.modular.eventbus.facade.launcher.IEventListener
import com.pengxr.modular.eventbus.facade.launcher.ModularEventBus
import com.pengxr.modular.eventbus.facade.template.BaseEvent
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import timber.log.Timber
import java.io.File
import java.io.IOException

/**
 * Created by HJW on 2023/5/11
 * 三方库相关初始化
 */
class ThirdInitializer(val application: Application) : AppInitializers {

    override fun init() {
        ApngImageLoader.getInstance().init(application)

        if (BuildConfig.DEBUG) {
            Timber.plant(Timber.DebugTree())
        } else {
            Timber.plant(NotLoggingTree())
        }
        SoftKeyboardGlobal.install(application, false)

        LoadingStateView.setViewDelegatePool {
            register(ToolbarViewDelegate())
        }
        /**
         * SVGA http缓存
         */
        val cacheDir = File(application.cacheDir, "http")
        HttpResponseCache.install(cacheDir, 1024 * 1024 * 200)
        EasyFloat.init(application, BuildConfig.DEBUG)

        LoadMoreModuleConfig.defLoadMoreView = CustomLoadMoreView()
        //设置全局默认配置（优先级最低，会被其他设置覆盖）
        SmartRefreshLayout.setDefaultRefreshInitializer { _, layout -> //全局设置（优先级最低）
            layout.setEnableLoadMore(false)
            layout.setEnableAutoLoadMore(false)
            layout.setEnableOverScrollDrag(true)
            layout.setEnableOverScrollBounce(true)
            layout.setEnableLoadMoreWhenContentNotFull(false)
            layout.setEnableScrollContentWhenRefreshed(true)
            layout.setHeaderMaxDragRate(3.0f)
        }
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout -> //全局设置header
            layout.setEnableHeaderTranslationContent(true)
            RefreshHeader(context)
        }
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, layout -> //全局设置footer
            layout.setEnableFooterTranslationContent(true)
            LoadMoreFooter(context)
        }

        ModularEventBus.debug(BuildConfig.DEBUG)
            .throwNullEventException(false)
            .setEventListener(object : IEventListener {
                override fun <T> onEventPost(eventName: String, event: BaseEvent<T>, data: T?) {
                    Timber.d("ModularEventBus发送事件 eventName: $eventName, event=$event data=$data")
                }
            })

        //NIMClient.initV2(application,  getSDKOptions(application))
        initLocalNimString()
    }

    /*private fun getSDKOptions(context: Context): SDKOptions {
        val options = SDKOptions()
        with(options) {
            this.appKey = "2d6abc076f434fc52320c7118de5fead"
            enableV2CloudConversation = true
            //在线多端同步未读数
            sessionReadAck = true
            // 采用异步加载SDK
            asyncInitSDK = true
            //禁止后台进程唤醒UI进程
            disableAwake = true
            useXLog = true
            enableBackOffReconnectStrategy = true
            checkManifestConfig = BuildConfig.DEBUG
            loginCustomTag = ClientType.Android.toString()
            notifyStickTopSession = true
            mixPushConfig = MixPushConfig().apply {
                fcmCertificateName = "VisualNovel"
            }
            if (BuildConfig.DEBUG) {
                sdkStorageRootPath = getAppCacheDir(context) + "/nim"
            }
        }
        return options
    }*/

    /**
     * 配置 APP 保存图片/语音/文件/log等数据的目录
     * 这里示例用SD卡的应用扩展存储目录
     */
    private fun getAppCacheDir(context: Context): String? {
        var storageRootPath: String? = null
        try {
            // SD卡应用扩展存储区(APP卸载后，该目录下被清除，用户也可以在设置界面中手动清除)，请根据APP对数据缓存的重要性及生命周期来决定是否采用此缓存目录.
            // 该存储区在API 19以上不需要写权限，即可配置 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18"/>
            if (context.externalCacheDir != null) {
                storageRootPath = context.externalCacheDir!!.canonicalPath
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        if (TextUtils.isEmpty(storageRootPath)) {
            // SD卡应用公共存储区(APP卸载后，该目录不会被清除，下载安装APP后，缓存数据依然可以被加载。SDK默认使用此目录)，该存储区域需要写权限!
            storageRootPath = Environment.getExternalStorageDirectory().toString() + "/" + context.packageName
        }
        return storageRootPath
    }

    private fun initLocalNimString() {
        /*NimStrings.DEFAULT.apply {
            status_bar_multi_messages_incoming = application.getString(R.string.status_bar_multi_messages_incoming)
            status_bar_ticker_text = application.getString(R.string.status_bar_ticker_text)
            status_bar_image_message = application.getString(R.string.status_bar_image_message)
            status_bar_audio_message = application.getString(R.string.status_bar_audio_message)
            status_bar_video_message = application.getString(R.string.status_bar_video_message)
            status_bar_file_message = application.getString(R.string.status_bar_file_message)
            status_bar_location_message = application.getString(R.string.status_bar_location_message)
            status_bar_notification_message = application.getString(R.string.status_bar_notification_message)
            status_bar_avchat_message = application.getString(R.string.status_bar_avchat_message)
            status_bar_tip_message = application.getString(R.string.status_bar_tip_message)
            status_bar_custom_message = application.getString(R.string.status_bar_custom_message)
            status_bar_unsupported_message = application.getString(R.string.status_bar_unsupported_message)
            status_bar_hidden_message_content = application.getString(R.string.status_bar_hidden_message_content)
            status_bar_hidden_message_title = application.getString(R.string.status_bar_hidden_message_title)
        }*/
    }

}