package com.ypsx.yppos

import android.content.Intent
import android.os.Build
import android.os.Process
import com.didichuxing.doraemonkit.DoKit
import com.didichuxing.doraemonkit.kit.AbstractKit
import com.elvishew.xlog.LogConfiguration
import com.elvishew.xlog.LogLevel
import com.elvishew.xlog.XLog
import com.elvishew.xlog.formatter.border.DefaultBorderFormatter
import com.elvishew.xlog.formatter.message.json.DefaultJsonFormatter
import com.elvishew.xlog.formatter.message.throwable.DefaultThrowableFormatter
import com.elvishew.xlog.formatter.message.xml.DefaultXmlFormatter
import com.elvishew.xlog.formatter.stacktrace.DefaultStackTraceFormatter
import com.elvishew.xlog.formatter.thread.DefaultThreadFormatter
import com.elvishew.xlog.printer.AndroidPrinter
import com.elvishew.xlog.printer.Printer
import com.elvishew.xlog.printer.file.FilePrinter
import com.elvishew.xlog.printer.file.backup.FileSizeBackupStrategy2
import com.elvishew.xlog.printer.file.backup.NeverBackupStrategy
import com.elvishew.xlog.printer.file.clean.FileLastModifiedCleanStrategy
import com.elvishew.xlog.printer.file.naming.DateFileNameGenerator
import com.hjq.toast.ToastUtils
import com.tencent.mmkv.MMKV
import com.ypsx.base.base.BaseApp
import com.ypsx.yppos.app.event.AppViewModel
import com.ypsx.yppos.app.event.EventViewModel
import com.ypsx.yppos.kit.ServerHostKit
import com.ypsx.yppos.room.database.PosDatabase
import com.ypsx.yppos.utils.PathUtils
import com.ypsx.yppos.utils.XLogFlattener
import com.ypsx.yppos.utils.dXLog

const val maxSize: Long = 1024 * 1024 * 50
const val maxTimeMillis: Long = 1000 * 60 * 60 * 24 * 30
const val maxBackupIndex: Int = 10


class PosApp : BaseApp() {

    companion object {
        lateinit var instance: PosApp
        lateinit var eventViewModelInstance: EventViewModel
        lateinit var appViewModelInstance: AppViewModel
    }

    override fun onCreate() {
        super.onCreate()
        MMKV.initialize(this)
        // 初始化 Toast 框架
        ToastUtils.init(this);
        var list = arrayListOf<AbstractKit>()
        list.add(ServerHostKit())
        DoKit.Builder(this)
            .customKits(listOf(ServerHostKit()))
            .build()
        instance = this
        PosDatabase.getDatabase(instance)
        eventViewModelInstance = getAppViewModelProvider().get(EventViewModel::class.java)
        appViewModelInstance = getAppViewModelProvider().get(AppViewModel::class.java)
        initXlog()


    }

    private fun initXlog() {
        val config = LogConfiguration.Builder()
            .logLevel(LogLevel.ALL)// 指定日志级别，低于该级别的日志将不会被打印，默认为 LogLevel.ALL
            .tag(getString(R.string.global_tag)) // 指定 TAG，默认为 "X-LOG"
            .enableThreadInfo() // 允许打印线程信息，默认禁止
            .enableStackTrace(2) // 允许打印深度为 2 的调用栈信息，默认禁止
            .enableBorder() // 允许打印日志边框，默认禁止
            .jsonFormatter(DefaultJsonFormatter()) // 指定 JSON 格式化器，默认为 DefaultJsonFormatter
            .xmlFormatter(DefaultXmlFormatter()) // 指定 XML 格式化器，默认为 DefaultXmlFormatter
            .throwableFormatter(DefaultThrowableFormatter()) // 指定可抛出异常格式化器，默认为 DefaultThrowableFormatter
            .threadFormatter(DefaultThreadFormatter()) // 指定线程信息格式化器，默认为 DefaultThreadFormatter
            .stackTraceFormatter(DefaultStackTraceFormatter()) // 指定调用栈信息格式化器，默认为 DefaultStackTraceFormatter
            .borderFormatter(DefaultBorderFormatter()) // 指定边框格式化器，默认为 DefaultBorderFormatter
            .build()

        val androidPrinter: Printer = AndroidPrinter(true) // 通过 android.util.Log 打印日志的打印器

//        val consolePrinter: Printer = ConsolePrinter() // 通过 System.out 打印日志到控制台的打印器

        val filePrinter: Printer = FilePrinter.Builder(PathUtils.getLogParent()) // 指定保存日志文件的路径
            .fileNameGenerator(DateFileNameGenerator()) // 指定日志文件名生成器，默认为 ChangelessFileNameGenerator("log")
            .backupStrategy(NeverBackupStrategy()) // 指定日志文件备份策略，默认为 FileSizeBackupStrategy(1024 * 1024)
            .backupStrategy(
                FileSizeBackupStrategy2(maxSize, maxBackupIndex)
            )             // Default: FileSizeBackupStrategy(1024 * 1024)
            .cleanStrategy(FileLastModifiedCleanStrategy(maxTimeMillis))     // Default: NeverCleanStrategy(), 7天
            .flattener(XLogFlattener()) // 指定日志平铺器，默认为 DefaultFlattener
            .build()

        XLog.init( // 初始化 XLog
            config,  // 指定日志配置，如果不指定，会默认使用 new LogConfiguration.Builder().build()
            androidPrinter,  // 添加任意多的打印器。如果没有添加任何打印器，会默认使用 AndroidPrinter(Android)/ConsolePrinter(java)
            filePrinter
        )

        val header = "\n>>>>>>>>>>>>>>>> File Header >>>>>>>>>>>>>>>>" +
                "\nDevice Manufacturer: " + Build.MANUFACTURER +
                "\nDevice Brand       : " + Build.BRAND +
                "\nDevice Model       : " + Build.MODEL +
                "\nAndroid Version    : " + Build.VERSION.RELEASE +
                "\nAndroid SDK        : " + Build.VERSION.SDK_INT +
                "\nApp VersionName    : " + BuildConfig.VERSION_NAME +
                "\nApp VersionCode    : " + BuildConfig.VERSION_CODE +
                "\n<<<<<<<<<<<<<<<< File Header <<<<<<<<<<<<<<<<\n\n";
       header.dXLog()

    }


    /**
     * 重启当前应用
     */
    fun restartApplication() {
        val intent = packageManager.getLaunchIntentForPackage(packageName)
        intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        startActivity(intent)
        Process.killProcess(Process.myPid())
    }


}