package com.idle.wall.idletool;

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

import androidx.annotation.NonNull;

import com.idle.wall.IdleApp;
import com.idle.wall.idleadapter.OnLikelist;
import com.idle.wall.idleadapter.OnUpdatelike;
import com.idle.wall.idleadapter.OnViewList; // 新增：导入浏览监听接口
import com.idle.wall.idlebean.IdleData;
import com.idle.wall.idlebean.IdleData_;
import com.idle.wall.idlebean.MyObjectBox;

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 ObectManager {

    private static BoxStore boxStore;
    private static Box<IdleData> LikeBox;
    private static List<OnUpdatelike> list = new ArrayList<>();

    public static void init(Context context) {
        boxStore = MyObjectBox.builder().androidContext(context).build();
    }
    public static void addData(List<IdleData> dataList) {
        synchronized (ObectManager.class) {
            for (IdleData data : dataList) {
                addData(data); // 复用原有单个添加逻辑
            }
        }
    }

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

    public static void addData(IdleData data) {
        Box<IdleData> objectBoxLike = getObjectBoxLike();
        String imId = data.getImId();
        IdleData first = objectBoxLike.query()
                .equal(IdleData_.imId, imId, QueryBuilder.StringOrder.CASE_SENSITIVE)
                .build()
                .findFirst();
        if (first == null) {
            objectBoxLike.put(data);
        } else {
        }
    }

    // ========== 你原有：setLikeDataListener（保留不变） ==========
    public static DataSubscription setLikeDataListener(OnLikelist listener) {
        Query<IdleData> build = getObjectBoxLike().query()
                .equal(IdleData_.isLike, true)
                .orderDesc(IdleData_.likeTime)
                .build();
        return build.subscribe(new DataSubscriptionList())
                .on(AndroidScheduler.mainThread())
                .observer(new DataObserver<List<IdleData>>() {
                    @Override
                    public void onData(@NonNull List<IdleData> data) {
                        listener.onLikeList(data);
                    }
                });
    }

    // ========== 你原有：updateLike（保留不变） ==========
    public static void updateLike(IdleData boxLike) {
        Box<IdleData> objectBoxLike = getObjectBoxLike();
        String imId = boxLike.getImId();

        if (boxLike.isLike()) {
            boxLike.setLikeTime(System.currentTimeMillis());
        } else {
            boxLike.setLikeTime(0);
        }

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

    // ========== 你原有：insertOrUpdateDownload（保留不变） ==========
    public static void insertOrUpdateDownload(IdleData boxLike) {
        Box<IdleData> objectBoxLike = getObjectBoxLike();
        String imId = boxLike.getImId();
        IdleData first = objectBoxLike.query()
                .equal(IdleData_.imId, imId, QueryBuilder.StringOrder.CASE_SENSITIVE)
                .build()
                .findFirst();
        if (first == null) {
            boxLike.setDownload(true);
            objectBoxLike.put(boxLike);
        } else {
            first.setDownload(true);
            objectBoxLike.put(first);
        }
    }

    // ========== 你原有：search（保留不变） ==========
    public static List<IdleData> search(String name) {
        Box<IdleData> objectBoxLike = getObjectBoxLike();
        List<IdleData> data = objectBoxLike.query()
                .contains(IdleData_.description, name, QueryBuilder.StringOrder.CASE_SENSITIVE)
                .build()
                .find();
        return data;
    }

    // ========== 你原有：queryHome（保留不变） ==========
    public static List<IdleData> queryHome(String name) {
        Box<IdleData> objectBoxLike = getObjectBoxLike();
        List<IdleData> data = objectBoxLike.query()
                .equal(IdleData_.categoryName, name, QueryBuilder.StringOrder.CASE_SENSITIVE)
                .build()
                .find(10, 1);
        return data;
    }

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

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

    public static List<IdleData> getViewList() {
        return getObjectBoxLike().query()
                .greater(IdleData_.viewTime, 0) // 仅查询有浏览记录的（viewTime>0）
                .orderDesc(IdleData_.viewTime)  // 最新浏览的排在前面
                .build()
                .find();
    }

    public static DataSubscription setViewDataListener(OnViewList listener) {
        Query<IdleData> build = getObjectBoxLike().query()
                .greater(IdleData_.viewTime, 0)
                .orderDesc(IdleData_.viewTime)
                .build();
        return build.subscribe(new DataSubscriptionList())
                .on(AndroidScheduler.mainThread())
                .observer(new DataObserver<List<IdleData>>() {
                    @Override
                    public void onData(@NonNull List<IdleData> data) {
                        listener.onViewList(data);
                    }
                });
    }
    public static void updateViewHistory(IdleData data) {
        if (data == null) return;
        IdleData existData = getObjectBoxLike().query()
                .equal(IdleData_.imId, data.getImId(), QueryBuilder.StringOrder.CASE_SENSITIVE)
                .build()
                .findFirst();
        if (existData != null) {
            existData.setViewTime(System.currentTimeMillis());
            getObjectBoxLike().put(existData);
        } else {
            data.setViewTime(System.currentTimeMillis());
            addData(data); // 复用你原有addData方法，避免重复添加
        }
    }
}