package com.example.quiz.data.repository;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.quiz.data.model.Course;
import com.example.quiz.data.model.PagedModel;
import com.example.quiz.data.model.ResponseError;
import com.example.quiz.data.remote.ApiService;
import com.example.quiz.utils.Result;
import com.google.gson.Gson;

import javax.inject.Inject;

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

public class CourseRepository {
    private ApiService apiService;
    private final Course.Statut OPENED_STATUT = Course.Statut.OUVERT;

    @Inject
    public CourseRepository(ApiService apiService) {
        this.apiService = apiService;
    }

    public LiveData<Result<PagedModel<Course>>> getCourses(String reunionDate) {
        MutableLiveData<Result<PagedModel<Course>>> liveCourses = new MutableLiveData<Result<PagedModel<Course>>>();
        liveCourses.setValue(Result.loading());
        apiService.getCourses(reunionDate,String.valueOf(OPENED_STATUT)).enqueue(new Callback<PagedModel<Course>>() {
            @Override
            public void onResponse(Call<PagedModel<Course>> call, Response<PagedModel<Course>> response) {
                if(response.isSuccessful()){
                    liveCourses.postValue(Result.success(response.body()));
                }else{
                    try{
                        String error = response.errorBody().string();
                        Gson gson = new Gson();
                        ResponseError errorResponse = gson.fromJson(error, ResponseError.class);
                        liveCourses.postValue(Result.error(errorResponse.getMessage()));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }

            @Override
            public void onFailure(Call<PagedModel<Course>> call, Throwable throwable) {
                liveCourses.postValue(Result.error(throwable.getMessage()));
            }
        });
        return liveCourses;
    }
}
