package com.wall.turing.wallpapers;

import android.app.Application;
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;

import com.tradplus.ads.open.TradPlusSdk;
import com.up.uploadlibrary.UpLoadManager;
import com.wall.turing.wallpapers.myselfbean.Wallpaper;
import com.wall.turing.wallpapers.uutils.AppUtils;
import com.wall.turing.wallpapers.uutils.JsonManager;
import com.wall.turing.wallpapers.uutils.DatabaseManager;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class WallpaperApplication extends Application {
    public static Context mAppContext;

    public static String TAG = "-------MyApp---------";
    public static Typeface defaultFont;


    private String animasName = "AnimalsTuring.json";
    private String exName = "ExperimentalTuring.json";
    private String filmName = "FilmTuring.json";
    private String natureName = "NatureTuring.json";
    private String pattName = "PatternsTuirng.json";
    private String streetName = "StreetTuring.json";
    private String travelName = "TravelTuring.json";
    private String wallpaperName = "FeaturedTuring.json";
    private ExecutorService executor;
    private static List<String> CategoryNames = new ArrayList<>();
    private int i = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        mAppContext = this;
        defaultFont = Typeface.createFromAsset(getAssets(), "custfont001.ttf");
        initSdk();
        DatabaseManager.init(this);
        executor = Executors.newFixedThreadPool(3);
        
        // 启动时只加载 Featured 数据
        String[] initialNames = {wallpaperName};
        
        // 保存所有分类名称
        CategoryNames.add("FeaturedTuring");
        CategoryNames.add("AnimalsTuring");
        CategoryNames.add("ExperimentalTuring");
        CategoryNames.add("FilmTuring");
        CategoryNames.add("NatureTuring");
        CategoryNames.add("PatternsTuirng");
        CategoryNames.add("StreetTuring");
        CategoryNames.add("TravelTuring");

        try {
            for (String name : initialNames) {
                InputStream open = getAssets().open(name);
                String covertStr = AppUtils.getCovertStr(open);
                if (!covertStr.isEmpty()) {
                    String realName = name.substring(0, name.indexOf("."));
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            Log.d(WallpaperApplication.TAG, "------------Loading " + realName);
                            List<Wallpaper> data = JsonManager.INSTANCE.getData(covertStr, realName);
                            Collections.shuffle(data);
                            for (Wallpaper data1 : data) {
                                DatabaseManager.addData(data1);
                            }
                            Log.d(WallpaperApplication.TAG, "------------Loaded " + realName + " with " + data.size() + " items");
                        }
                    });
                }
            }
            
            // 延迟加载其他分类数据
            loadOtherCategories();

        } catch (IOException e) {
            Log.e(TAG, "Error loading initial data", e);
        }
    }
    
    // 延迟加载其他分类数据
    private void loadOtherCategories() {
        new Thread(() -> {
            try {
                // 等待2秒
                Thread.sleep(2000);
                
                String[] otherNames = {animasName, exName, filmName, natureName, pattName, streetName, travelName};
                
                for (String name : otherNames) {
                    try {
                        InputStream open = getAssets().open(name);
                        String covertStr = AppUtils.getCovertStr(open);
                        if (!covertStr.isEmpty()) {
                            String realName = name.substring(0, name.indexOf("."));
                            executor.execute(() -> {
                                Log.d(WallpaperApplication.TAG, "------------Loading category: " + realName);
                                List<Wallpaper> data = JsonManager.INSTANCE.getData(covertStr, realName);
                                Collections.shuffle(data);
                                for (Wallpaper data1 : data) {
                                    DatabaseManager.addData(data1);
                                }
                                Log.d(WallpaperApplication.TAG, "------------Loaded category: " + realName + " with " + data.size() + " items");
                            });
                        }
                        // 每个文件之间间隔500ms，避免内存峰值
                        Thread.sleep(500);
                    } catch (Exception e) {
                        Log.e(TAG, "Error loading category: " + name, e);
                    }
                }
                
            } catch (InterruptedException e) {
                Log.e(TAG, "Error in delayed loading", e);
            }
        }).start();


    }

    public static List<String> getCategoryNames() {
        return CategoryNames;
    }


    private void initSdk(){
        TradPlusSdk.initSdk(this, "699848D557C44D76C1AEB0468E108D11");

        UpLoadManager.INSTANCE.init(this, "TURING_up_load", (s, s2) -> null);
    }
}
