package com.example.tampopo_client.viewmodels;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.tampopo_client.models.FriendRequest;
import com.example.tampopo_client.resources.FriendRequestsResource;

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

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class FriendReceivedRequestViewModel extends ViewModel {
    // サーバー(API)と通信するためのツール
    private final Retrofit retrofit;
    // API の窓口
    private final FriendRequestsResource friendRequestsResource;
    // 自分が受け取った申請
    private final MutableLiveData<List<FriendRequest>> receivedRequests;
    // 通信結果の状態
    private final MutableLiveData<String> operationResult;

    // 直近で使用したユーザーIDをキャッシュしておく
    private String cachedUserId;
    private String cachedToken;

    public FriendReceivedRequestViewModel() {
        this.retrofit = new Retrofit.Builder()
                .baseUrl("http://nitta-lab-www.is.konan-u.ac.jp/tampopo/")
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(JacksonConverterFactory.create())
                .build();

        this.friendRequestsResource = retrofit.create(FriendRequestsResource.class);
        this.receivedRequests = new MutableLiveData<>(new ArrayList<>());
        this.operationResult = new MutableLiveData<>();
    }

    // viewがobserve出来るように
    public MutableLiveData<List<FriendRequest>> getReceivedRequestsLiveData() {
        return receivedRequests;
    }

    public MutableLiveData<String> getOperationResultLiveData() {
        return operationResult;
    }

    // サーバーから受け取った FriendRequest のデータを読み込む
    public void loadReceivedRequests(String token, String myUserId) {
        // キャッシュ保存（削除後の再読み込み用）
        this.cachedUserId = myUserId;
        this.cachedToken = token;

        Call<List<FriendRequest>> call = friendRequestsResource.getFriendRequests(token);
        call.enqueue(new Callback<List<FriendRequest>>() {
            @Override
            public void onResponse(Call<List<FriendRequest>> call, Response<List<FriendRequest>> response) {
                if (response.isSuccessful()) {
                    List<FriendRequest> allRequests = response.body();
                    if (allRequests == null) allRequests = new ArrayList<>();

                    // ✅ 自分が受け取ったものだけを抽出
                    List<FriendRequest> receivedOnly = new ArrayList<>();
                    for (FriendRequest req : allRequests) {
                        if (req.getReceiverId() != null && req.getReceiverId().equals(myUserId)) {
                            receivedOnly.add(req);
                        }
                    }

                    receivedRequests.setValue(receivedOnly);
                    operationResult.setValue("Success (filtered " + receivedOnly.size() + " requests)");
                    System.out.println("Success SetValue (filtered): " + receivedOnly);

                } else {
                    operationResult.setValue("Error: " + response.code());
                    System.out.println("Response error: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<List<FriendRequest>> call, Throwable t) {
                operationResult.setValue("Network error: " + t.getMessage());
                System.out.println("Network error: " + t);
            }
        });
    }

    // フレンドリクエスト削除メソッド
    public void deleteFriendRequest(String friendRequestId, String token) {
        Call<Void> call = friendRequestsResource.deleteFriendRequest(friendRequestId, token);

        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    operationResult.setValue("Friend request deleted successfully.");
                    System.out.println("Deleted friend request ID: " + friendRequestId);

                    // ✅ キャッシュがある場合は再読み込み
                    if (cachedToken != null && cachedUserId != null) {
                        loadReceivedRequests(cachedToken, cachedUserId);
                    }

                } else {
                    operationResult.setValue("Error deleting request: " + response.code());
                    System.out.println("Error deleting request: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                operationResult.setValue("Network error: " + t.getMessage());
                System.out.println("Network error: " + t);
            }
        });
    }
}




