package com.example.iot_controlhost;

import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.provider.Settings;
import android.view.Gravity;

import com.example.iot_controlhost.model.DaoMaster;
import com.example.iot_controlhost.model.DaoSession;
import com.example.iot_controlhost.utils.MMKVUtil;
import com.example.iot_controlhost.utils.MyUtil;
import com.example.iot_controlhost.utils.global.AutoModelSet;
import com.example.iot_controlhost.utils.global.HardwareSetting;
import com.example.iot_controlhost.utils.global.RoomSetting;
import com.example.iot_controlhost.utils.global.SpinnerList;
import com.example.iot_controlhost.utils.global.Variable;
import com.example.iot_controlhost.utils.log.CrashHandlerUtil;
import com.example.iot_controlhost.utils.log.MyLog;
import com.example.iot_controlhost.utils.log.UserLog;
import com.example.iot_controlhost.utils.mainboard.MyAPIContext;
import com.example.iot_controlhost.utils.network.Url;
import com.example.iot_controlhost.utils.old.OldSet;
import com.example.iot_controlhost.utils.timer.ThemeTaskUtil;
import com.example.iot_controlhost.utils.timer.TimerTaskUtil;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import org.xutils.BuildConfig;
import org.xutils.x;

import java.io.File;

import es.dmoral.toasty.Toasty;
import timber.log.Timber;

public class MyApp extends Application {
    private static DaoSession mSession;
    private static MyApp instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        // 初始化网络请求地址
        Url.initUrl();
        // 初始化MMKV
        MMKVUtil.init();
        // 初始化数据库
        initDb();
        // 初始化崩溃捕捉
        CrashHandlerUtil.getInstance().init(getApplicationContext());
        // 初始化日志库
        Timber.plant(new MyLog());
        Timber.plant(new UserLog());
        UserLog.system("软件生命周期", "软件启动，版本=" + BuildConfig.VERSION_NAME);
        MyLog.app("软件生命周期：进程启动，版本=" + BuildConfig.VERSION_NAME
                + "，versionCode=" + BuildConfig.VERSION_CODE
                + "，Android=" + android.os.Build.VERSION.RELEASE
                + "，SDK=" + android.os.Build.VERSION.SDK_INT);
        if (OldSet.isFirstTime()) {
            OldSet.importOldSet(getApplicationContext());
        }
        MMKVUtil.put(HardwareSetting.HOST_ID, Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID));
        // 初始化亮暗主题
        initTheme();
        // 初始化网络请求库
        x.Ext.init(this);
        // 初始化Toast
        Toasty.Config
                .getInstance()
                .tintIcon(true)
                .setTextSize(30)
                .allowQueue(false)
                .setGravity(Gravity.CENTER)
                .supportDarkTheme(true)
                .apply();
        // 初始化主板Api
        MyAPIContext.getInstance().init();
        MyAPIContext.getInstance().feet();
        // 初始化调试任务
        initDebug(false);
        // 初始化每日定时任务
        TimerTaskUtil.start();
    }


    /**
     * 在调试时使用的代码
     */
    private void initDebug(boolean isDebug) {
        if (isDebug) {
            //在新主机上测试用代码：
            MMKVUtil.put(RoomSetting.AREA_CODE, "5f645faa");
            MMKVUtil.put(HardwareSetting.HOST_ID, "2af30b4c49d4b26b");
            MMKVUtil.put(HardwareSetting.IS_REGISTERED, false);
        }
        MyLog.test("(区域码)AREA_CODE: " + RoomSetting.getAreaCode());
        MyLog.test("(设备码)HOST_ID: " + HardwareSetting.getHostId());
    }

    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator((context, layout) -> {
//            layout.setPrimaryColorsId(R.color.md_theme_light_primary, R.color.md_theme_light_secondary, R.color.md_theme_light_tertiary);//全局设置主题颜色
            return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator((context, layout) -> new ClassicsFooter(context).setDrawableSize(20));
    }

    /**
     * 连接数据库并创建会话
     */
    public void initDb() {
        deleteDatabase(this, "lot.db");
        // 获取需要连接的数据库
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this, "lot240827.db");
        SQLiteDatabase db = devOpenHelper.getWritableDatabase();
        // 创建数据库连接
        DaoMaster daoMaster = new DaoMaster(db);
        // 创建数据库会话
        mSession = daoMaster.newSession();
    }

    public static Context getAppContext() {
        return instance.getApplicationContext();
    }

    // 删除数据库的方法
    public void deleteDatabase(Context context, String dbName) {
        // 获取数据库文件的路径
        File dbFile = context.getDatabasePath(dbName);

        // 删除数据库文件
        if (dbFile.exists()) {
           dbFile.delete();
        }
    }
    /**
     * 初始化亮暗主题
     */
    private void initTheme() {
        boolean isDark;
        if (RoomSetting.getAutoLightNight()) {
            isDark = ThemeTaskUtil.resetTask();
        } else {
            isDark = RoomSetting.isDarkTheme();
        }
        MyUtil.switchDarkMode(isDark);
    }

    /**
     * 供外接使用
     */
    public static DaoSession getDaoSession() {
        return mSession;
    }

}
