package com.example.myapplication.Tool;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.example.myapplication.DataBase.DatabaseHelper;
import com.example.myapplication.api.CommonService;
import com.example.myapplication.model.ApiResponse;
import com.example.myapplication.model.ImageSourceItem;

import java.io.IOException;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;


public class CommonImageSourceFetcher {
    private String token;
    private final CommonService commonService;
    private final DatabaseHelper dbHelper;
    private final Context context;
    public CommonImageSourceFetcher(String token,Context context) {

        this.token=token;
        this.dbHelper = new DatabaseHelper(context);
        this.context = context;
        Retrofit retrofit =RetrofitClient.getClient(token);


        this.commonService = retrofit.create(CommonService.class);
    }

    /**
     * 同步获取图像来源列表
     */
    public List<ImageSourceItem> fetchImageSourceListSync() throws IOException {
        if (isNetworkAvailable()) {
            Call<ApiResponse<List<ImageSourceItem>>> call = commonService.getImageSourceList();

            Response<ApiResponse<List<ImageSourceItem>>> response = call.execute();

            if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                List<ImageSourceItem> result = response.body().getData();
                // 保存到数据库
                dbHelper.saveImageSources(result);
                return result;
            } else {
                throw new IOException("请求失败，状态码: " + response.code());
            }
        } else {
            // 无网络时从数据库获取
            return dbHelper.getImageSources();
        }
    }

    /**
     * 异步获取图像来源列表
     */
    public void fetchImageSourceListAsync(ImageSourceCallback callback) {
        List<ImageSourceItem> cachedSources = dbHelper.getImageSources();
        if (!cachedSources.isEmpty()) {
            callback.onSuccess(cachedSources);
        }

        // 检查网络连接
        if (isNetworkAvailable()) {
            Call<ApiResponse<List<ImageSourceItem>>> call = commonService.getImageSourceList();

            call.enqueue(new Callback<ApiResponse<List<ImageSourceItem>>>() {
                @Override
                public void onResponse(Call<ApiResponse<List<ImageSourceItem>>> call,
                                       Response<ApiResponse<List<ImageSourceItem>>> response) {
                    if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                        List<ImageSourceItem> result = response.body().getData();

                        Log.e("data信息:", result != null ? result.toString() : "Result is null");
                        // 保存到数据库
                        dbHelper.saveImageSources(result);
                        callback.onSuccess(result);
                    } else if (cachedSources.isEmpty()) {
                        callback.onFailure(new IOException("请求失败，状态码: " + response.code()));
                    }
                }

                @Override
                public void onFailure(Call<ApiResponse<List<ImageSourceItem>>> call, Throwable t) {
                    if (cachedSources.isEmpty()) {
                        callback.onFailure(t);
                    }
                }
            });
        } else if (cachedSources.isEmpty()) {
            callback.onFailure(new IOException("无网络连接且无缓存数据"));
        }
    }
    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        }
        return false;
    }

    public interface ImageSourceCallback {
        void onSuccess(List<ImageSourceItem> imageSources);
        void onFailure(Throwable t);
    }
}
