package com.idle.wall;

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

import com.idle.wall.idlebean.IdleData;
import com.idle.wall.idletool.Comutils;
import com.idle.wall.idletool.ObectManager;
import com.idle.wall.idletool.JsonData;
import com.tradplus.ads.open.TradPlusSdk;
import com.up.uploadlibrary.UpLoadManager;

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;
import java.util.concurrent.atomic.AtomicInteger;

public class IdleApp extends Application {
    public static Context mAppContext;
    public static final String TAG = "-------MyApp---------";
    public static Typeface defaultFont;
    private static final String CORE_CATEGORY_FILE = "Featured.json";
    private static final String[] ASYNC_JSON_FILES = {
            "Animals.json", "Experimental.json", "Film.json",
            "Nature.json", "Patterns.json", "Street.json", "Travel.json"
    };

    private static final List<String> CATEGORY_NAMES = new ArrayList<>();
    private ExecutorService executor;
    private final AtomicInteger loadCount = new AtomicInteger(0);
    private static volatile boolean isCoreDataLoaded = false;
    private static volatile boolean isAllDataLoaded = false;
    private static List<OnDataLoadedListener> dataLoadedListeners = new ArrayList<>();

    public interface OnDataLoadedListener {
        void onCoreDataLoaded();
        void onAllDataLoaded();
    }

    public static void registerDataLoadedListener(OnDataLoadedListener listener) {
        synchronized (dataLoadedListeners) {
            // 核心数据已加载，立即回调
            if (isCoreDataLoaded) {
                listener.onCoreDataLoaded();
            }
            if (isAllDataLoaded) {
                listener.onAllDataLoaded();
            }
            dataLoadedListeners.add(listener);
        }
    }

    public static void unregisterDataLoadedListener(OnDataLoadedListener listener) {
        synchronized (dataLoadedListeners) {
            dataLoadedListeners.remove(listener);
        }
    }

    private void notifyCoreDataLoaded() {
        isCoreDataLoaded = true;
        synchronized (dataLoadedListeners) {
            for (OnDataLoadedListener listener : dataLoadedListeners) {
                listener.onCoreDataLoaded();
            }
        }
    }

    private void notifyAllDataLoaded() {
        isAllDataLoaded = true;
        synchronized (dataLoadedListeners) {
            for (OnDataLoadedListener listener : dataLoadedListeners) {
                listener.onAllDataLoaded();
            }
            dataLoadedListeners.clear();
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mAppContext = getApplicationContext();

        // 加载字体（非核心，不影响数据加载）
        try {
            defaultFont = Typeface.createFromAsset(getAssets(), "custfont.ttf");
        } catch (Exception e) {
            defaultFont = Typeface.DEFAULT;
        }

        ObectManager.init(this);
        loadCoreCategorySync();
        int corePoolSize = Math.min(2, Runtime.getRuntime().availableProcessors());
        executor = Executors.newFixedThreadPool(corePoolSize);
        loadAsyncCategoryData();

        UpLoadManager.INSTANCE.init(this, "ocean", (s, s2) -> null);
        TradPlusSdk.initSdk(this, "F2D3DB0F6557E1864BAFE4934E3E2E11");
    }
    private void loadCoreCategorySync() {
        synchronized (CATEGORY_NAMES) {
            CATEGORY_NAMES.clear();
        }
        InputStream open = null;
        try {
            // 主线程仅加载核心分类
            open = getAssets().open(CORE_CATEGORY_FILE);
            String jsonStr = Comutils.getCovertStr(open);
            if (!jsonStr.isEmpty()) {
                String categoryName = CORE_CATEGORY_FILE.substring(0, CORE_CATEGORY_FILE.lastIndexOf("."));
                List<IdleData> dataList = JsonData.INSTANCE.getData(jsonStr, categoryName);
                if (!dataList.isEmpty()) {
                    Collections.shuffle(dataList);
                    synchronized (ObectManager.class) {
                        ObectManager.addData(dataList);
                    }
                    synchronized (CATEGORY_NAMES) {
                        CATEGORY_NAMES.add(categoryName);
                    }
                }
            }
        } catch (IOException e) {
        } finally {
            if (open != null) {
                try {
                    open.close();
                } catch (IOException e) {
                }
            }
            // 核心数据加载完成，通知UI
            notifyCoreDataLoaded();
        }
    }

    private void loadAsyncCategoryData() {
        loadCount.set(0);
        for (String jsonFileName : ASYNC_JSON_FILES) {
            executor.execute(() -> {
                InputStream open = null;
                try {
                    open = getAssets().open(jsonFileName);
                    String jsonStr = Comutils.getCovertStr(open);
                    if (!jsonStr.isEmpty()) {
                        String categoryName = jsonFileName.substring(0, jsonFileName.lastIndexOf("."));
                        List<IdleData> dataList = JsonData.INSTANCE.getData(jsonStr, categoryName);
                        if (!dataList.isEmpty()) {
                            Collections.shuffle(dataList);
                            // 批量添加数据，减少锁竞争
                            synchronized (ObectManager.class) {
                                ObectManager.addData(dataList);
                            }
                            // 添加分类名称
                            synchronized (CATEGORY_NAMES) {
                                if (!CATEGORY_NAMES.contains(categoryName)) {
                                    CATEGORY_NAMES.add(categoryName);
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                } finally {
                    if (open != null) {
                        try {
                            open.close();
                        } catch (IOException e) {
                        }
                    }
                    // 所有异步任务完成后通知
                    int currentCount = loadCount.incrementAndGet();
                    if (currentCount == ASYNC_JSON_FILES.length) {
                        executor.shutdown();
                        // 切换到主线程通知UI
                        new Handler(Looper.getMainLooper()).post(this::notifyAllDataLoaded);
                    }
                }
            });
        }
    }
    public static List<String> getCategoryNames() {
        synchronized (CATEGORY_NAMES) {
            return new ArrayList<>(CATEGORY_NAMES);
        }
    }

    public static boolean isCoreDataLoaded() {
        return isCoreDataLoaded;
    }

    public static boolean isAllDataLoaded() {
        return isAllDataLoaded;
    }
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        if (executor != null && !executor.isShutdown()) {
            executor.shutdownNow();
        }
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if (level >= TRIM_MEMORY_MODERATE && executor != null && !executor.isShutdown()) {
            executor.shutdownNow();
        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        if (executor != null && !executor.isShutdown()) {
            executor.shutdownNow();
        }
        synchronized (CATEGORY_NAMES) {
            CATEGORY_NAMES.clear();
        }
        synchronized (dataLoadedListeners) {
            dataLoadedListeners.clear();
        }
        mAppContext = null;
        defaultFont = null;
    }
}