package com.example.myapplicationnews.api;

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

import androidx.lifecycle.MutableLiveData;

import com.example.myapplicationnews.BuildConfig;
import com.example.myapplicationnews.api.model.NewsResponse;

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

public class NewsRepository {
    private static final String TAG = "NewsRepository";

    private static NewsRepository newsRepository;

    public static NewsRepository getInstance(Context context){
        if (newsRepository == null){
            newsRepository = new NewsRepository(context);
        }
        return newsRepository;
    }

    private NewsApi newsApi;

    public NewsRepository(Context context){
        newsApi = RetrofitService.createService(context, NewsApi.class);
    }

    public MutableLiveData<NewsResponse> getNews(String source, String key){
        final MutableLiveData<NewsResponse> newsData = new MutableLiveData<>();
        newsApi.getNewsList(source, key).enqueue(new Callback<NewsResponse>() {
            @Override
            public void onResponse(Call<NewsResponse> call,
                                   Response<NewsResponse> response) {
                if (response.isSuccessful()){
                    newsData.setValue(response.body());
                }
            }

            @Override
            public void onFailure(Call<NewsResponse> call, Throwable t) {
                newsData.setValue(null);
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "onFailure " + t.getStackTrace());
                }
            }
        });
        return newsData;
    }
}
