package com.bc_chat.bc_base

import android.app.Activity
import android.content.Context
import android.os.SystemClock
import com.alibaba.android.arouter.launcher.ARouter
import com.bc_chat.bc_base.ImService.ImRongService
import com.sinata.download.DownloadLibrary
import com.tencent.bugly.crashreport.CrashReport
import com.umeng.commonsdk.UMConfigure
import com.umeng.socialize.PlatformConfig
import com.zhaohaoting.framework.application.ZhtApplication
import com.zhaohaoting.framework.imagepicker.ImagePicker
import com.zhaohaoting.framework.imagepicker.ZImageLoader
import com.zhaohaoting.framework.imagepicker.view.CropImageView
import com.zhaohaoting.framework.requset.rxjava_retrofit.RxResultSubscriber
import com.zhaohaoting.framework.utils.DensityUtil
import com.zhaohaoting.framework.utils.file.FileUtils
import com.zhaohaoting.framework.utils.observer.Observer
import com.zhaohaoting.framework.utils.observer.ObserverManager

/**
 * author：Created by zhaohaoting on 2019/2/20
 * email：526309416@qq.com
 * desc：
 */
class BCApplication : ZhtApplication(), Observer<Any> {

    private var toLoginTime: Long = 0L

    override fun onEvent(key: String, var1: Any?) {
        if (key.equals(RxResultSubscriber.OBSERVER_REQUEST_ERROR)) {
            var code: Int = var1 as Int
            if (code == -2) { //冻结
                val currentTimeMillis = System.currentTimeMillis()
                if (currentTimeMillis - toLoginTime > 1000) {
                    ARouter.getInstance().navigation(ImRongService::class.java).loginOut(this)
                }
                toLoginTime = currentTimeMillis
            }
        }
    }

    private fun initImagePicker(mContext: Context, maxImgCount: Int) {
        val imagePicker = ImagePicker.getInstance()
        imagePicker.imageLoader = ZImageLoader()   //设置图片加载器
        imagePicker.isShowCamera = true                      //显示拍照按钮
        imagePicker.isCrop = true                           //允许裁剪（单选才有效）
        imagePicker.isSaveRectangle = true                   //是否按矩形区域保存
        imagePicker.selectLimit = maxImgCount              //选中数量限制
        imagePicker.style = CropImageView.Style.RECTANGLE  //裁剪框的形状
        imagePicker.focusWidth = DensityUtil.getScreenWidth(mContext)//裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.focusHeight = (DensityUtil.getScreenWidth(mContext) * 1.2).toInt()                     //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.outPutX = 1000                         //保存文件的宽度。单位像素
        imagePicker.outPutY = 1000                         //保存文件的高度。单位像素
        imagePicker.isMultiMode = true
        imagePicker.mediaType = ImagePicker.MEDIA_TYPE_IMAGE
    }

    override fun onCreate() {
        super.onCreate()
        if (isMainProcess) {
            initRouter()
            DownloadLibrary.init(
                    this, resources.getIdentifier(
                    "ic_launcher", "mipmap",
                    packageName
            ), null, FileUtils.getPackageName()
            )
            ARouter.getInstance().navigation(ImRongService::class.java)?.initRongIm(this)
            ObserverManager.getInstance().registerObserver(RxResultSubscriber.OBSERVER_REQUEST_ERROR, this)
            if (BuildConfig.DEBUG) UMConfigure.setLogEnabled(true)
            UMConfigure.init(this, "5caaee6d0cafb205e30016ab", "umeng", UMConfigure.DEVICE_TYPE_PHONE, "")
            PlatformConfig.setWeixin("wxcb0ebe2f93f05b64", "2b6fadfbfbeb643fad7374f6d91bc892")
            initImagePicker(this, 9)

            initBugly();
        }
    }

    private fun initBugly() {
        CrashReport.initCrashReport(getApplicationContext());
    }

    override fun getSpName(): String {
        return "bc_preferences"
    }

    override fun getIcLauncher(): Int {
        return resources.getIdentifier("ic_launcher", "mipmap", packageName)
    }

    override fun getEntranceActivity(): Class<out Activity>? {
        return null
    }

    private fun initRouter() {
        // 这两行必须写在init之前，否则这些配置在init过程中将无效
        if (BuildConfig.DEBUG) {
            //打印日志
            ARouter.openLog()
            //开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！
            //线上版本需要关闭,否则有安全风险)
            ARouter.openDebug()
        }
        // 尽可能早，推荐在Application中初始化
        ARouter.init(this)
    }
}
