package com.wall.photography.picture.tool;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;

import com.wall.photography.picture.MyApp;
import com.wall.photography.picture.Data.Data;
import com.wall.photography.picture.Data.Data_;
import com.wall.photography.picture.Data.MyObjectBox;
import com.wall.photography.picture.Connect.OnUpdateLike;
import com.wall.photography.picture.Connect.LikeList;

import java.util.ArrayList;
import java.util.List;

import io.objectbox.Box;
import io.objectbox.BoxStore;
import io.objectbox.android.AndroidScheduler;
import io.objectbox.query.Query;
import io.objectbox.query.QueryBuilder;
import io.objectbox.reactive.DataObserver;
import io.objectbox.reactive.DataSubscription;
import io.objectbox.reactive.DataSubscriptionList;

public class ObjectBoxManager {

    private static BoxStore boxStore;

    private static Box<Data> LikeBox;


    private static List<OnUpdateLike> list = new ArrayList<>();


    public static void init(Context context) {
        boxStore = MyObjectBox.builder().androidContext(context).build();
    }

    public static Box<Data> getObjectBoxLike() {
        if (LikeBox == null) {
            LikeBox = boxStore.boxFor(Data.class);
        }

        return LikeBox;
    }

    public static void addData(Data data) {
        Box<Data> objectBoxLike = getObjectBoxLike();
        String imId = data.getImId();
        Data first = objectBoxLike.query()
                .equal(Data_.imId, imId, QueryBuilder.StringOrder.CASE_SENSITIVE)
                .build()
                .findFirst();
        if (first == null) {
            Log.d(MyApp.TAG, "-----------addData " + imId);
            objectBoxLike.put(data);
        }else {
            Log.d(MyApp.TAG, "-----------忽略添加 ");
        }

    }

    public static DataSubscription setLikeDataListener(LikeList listener) {
        Query<Data> build = getObjectBoxLike().query()
                .equal(Data_.isLike, true)
                .build();
        return build.subscribe(new DataSubscriptionList())
                .on(AndroidScheduler.mainThread())
                .observer(new DataObserver<List<Data>>() {
                    @Override
                    public void onData(@NonNull List<Data> data) {
                        Log.d(MyApp.TAG, "------data=" + data.size());
                        listener.onLikeList(data);
                    }
                });

    }


    public static void updateLike(Data boxLike) {
        Box<Data> objectBoxLike = getObjectBoxLike();
        String imId = boxLike.getImId();

        objectBoxLike.put(boxLike);
        for (OnUpdateLike listener : list) {
            listener.onAdd(boxLike);
        }


    }


    public static void insertOrUpdateDownload(Data boxLike) {
        Box<Data> objectBoxLike = getObjectBoxLike();
        String imId = boxLike.getImId();
        Data first = objectBoxLike.query()
                .equal(Data_.imId, imId, QueryBuilder.StringOrder.CASE_SENSITIVE)
                .build()
                .findFirst();
        if (first == null) {
            Log.d(MyApp.TAG, "-----------添加11 Download=" + imId);
            boxLike.setDownload(true);
            objectBoxLike.put(boxLike);
        } else {
            first.setDownload(true);
            objectBoxLike.put(first);
            Log.d(MyApp.TAG, "-----------已经存在添加22 Download=" + imId);
        }

    }




    public static List<Data> search(String name) {
        Box<Data> objectBoxLike = getObjectBoxLike();
        List<Data> data = objectBoxLike.query()
                .contains(Data_.description, name, QueryBuilder.StringOrder.CASE_SENSITIVE)
                .build()
                .find();
        return data;
    }
    public static List<Data> queryHome(String name) {
        Box<Data> objectBoxLike = getObjectBoxLike();
        List<Data> data = objectBoxLike.query()
                .equal(Data_.categoryName, name, QueryBuilder.StringOrder.CASE_SENSITIVE)
                .build()
                .find(10, 1);
        return data;

    }
    public static List<Data> queryCategoryAll(String name) {
        Box<Data> objectBoxLike = getObjectBoxLike();
        List<Data> data = objectBoxLike.query()
                .equal(Data_.categoryName, name, QueryBuilder.StringOrder.CASE_SENSITIVE)
                .build()
                .find(0, 200);
        return data;

    }
    public static boolean queryIsLike(String imId) {
        Box<Data> objectBoxLike = getObjectBoxLike();
        Data first = objectBoxLike.query()
                .equal(Data_.imId, imId, QueryBuilder.StringOrder.CASE_SENSITIVE)
                .build()
                .findFirst();
        if (first != null && first.isLike()) {
            return true;
        } else {
            return false;
        }
    }

    public static List<Data> queryAllWallpapers(int limit) {
        Box<Data> objectBoxLike = getObjectBoxLike();
        List<Data> data = objectBoxLike.query()
                .build()
                .find(0, limit);
        return data;
    }

    /**
     * 根据标签类型查询壁纸
     * 将Feature、Animal、Film映射到不同的分类
     */
    public static List<Data> queryWallpapersByTag(String tagType, int limit) {
        Box<Data> objectBoxLike = getObjectBoxLike();
        List<Data> data = new ArrayList<>();
        
        // 将标签映射到多个分类，实现分类功�?
        List<String> categories = getCategoriesForTag(tagType);
        
        if (categories != null && !categories.isEmpty()) {
            // 查询多个分类的壁�?
            for (String category : categories) {
                List<Data> categoryData = objectBoxLike.query()
                        .equal(Data_.categoryName, category, QueryBuilder.StringOrder.CASE_SENSITIVE)
                        .build()
                        .find(0, limit / categories.size() + 1);
                data.addAll(categoryData);
                
                // 如果已经达到限制，退�?
                if (data.size() >= limit) {
                    break;
                }
            }
            
            // 如果数据超过限制，截取前limit�?
            if (data.size() > limit) {
                data = data.subList(0, limit);
            }
        } else {
            // 如果没有匹配的分类，返回所有壁�?
            data = objectBoxLike.query()
                    .build()
                    .find(0, limit);
        }
        
        return data;
    }
    
    /**
     * 根据标签类型获取对应的分类列表
     */
    private static List<String> getCategoriesForTag(String tagType) {
        List<String> categories = new ArrayList<>();
        
        switch (tagType) {
            case "Feature":
                // Feature标签对应：Featuredsearch（JSON文件名去掉.json后缀）
                categories.add("Featuredsearch");
                break;
            case "Animal":
                // Animal标签对应：Animalssearch（JSON文件名去掉.json后缀）
                categories.add("Animalssearch");
                break;
            case "Film":
                // Film标签对应：Filmsearch（JSON文件名去掉.json后缀）
                categories.add("Filmsearch");
                break;
            default:
                // 默认返回所有分类
                break;
        }
        
        return categories;
    }
    
    /**
     * 获取所有分类名称（对应JSON文件名去掉.json后缀）
     */
    public static List<String> getAllCategories() {
        List<String> categories = new ArrayList<>();
        categories.add("Featuredsearch");
        categories.add("Animalssearch");
        categories.add("Experimentalsearch");
        categories.add("Filmsearch");
        categories.add("Naturesearch");
        categories.add("Patternssearch");
        categories.add("Streetsearch");
        categories.add("Travelsearch");
        return categories;
    }


}

