package it.polimi.dima.giftlist.product.Rest;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import de.greenrobot.event.EventBus;
import it.polimi.dima.giftlist.model.exceptions.rest.ServerErrorException;
import it.polimi.dima.giftlist.model.exceptions.rest.UnknownErrorException;
import it.polimi.dima.giftlist.product.converter.CurrencyDownloader;
import it.polimi.dima.giftlist.product.converter.CurrentRates;
import it.polimi.dima.giftlist.product.converter.RetrofitEvent;
import it.polimi.dima.giftlist.util.HttpErrors;
import okhttp3.OkHttpClient;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.concurrent.Semaphore;

import javax.inject.Inject;

import it.polimi.dima.giftlist.BuildConfig;
import it.polimi.dima.giftlist.base.HttpLoggingInterceptor;
import it.polimi.dima.giftlist.base.Repository;
import it.polimi.dima.giftlist.model.EtsyProduct;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;

/**
 * Created by Elena on 27/01/2016.
 */
public class EtsyRestDataSource implements Repository {
    private final EtsyApi mEtsyApi;
    //private final GithubService mGithubService;
    public final static int MAX_ATTEMPS = 3;

    CurrencyDownloader mCurrencyDownloader;

    CurrentRates.RateList mRateList;

    EventBus mEventBus;

    @Inject
    public EtsyRestDataSource() {


        mCurrencyDownloader = new CurrencyDownloader();
        mEventBus = EventBus.getDefault();
        //logging interceptor
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        //authentication interceptor: appends the api_key
        EtsySigningInterceptor signingIterceptor = new EtsySigningInterceptor(BuildConfig.ETSY_API_KEY);

        //This is for adding interceptors
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(signingIterceptor)
                .addInterceptor(logging)
                .build();

        Gson customGsonInstance = new GsonBuilder()
                .registerTypeAdapter(new TypeToken<List<EtsyProduct>>() {}.getType(),
                        new EtsyResultsDeserializer())
                .create();

        Retrofit etsyApiAdapter = new Retrofit.Builder()
                .baseUrl(EtsyApi.END_POINT)
                .addConverterFactory(GsonConverterFactory.create(customGsonInstance))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();

        mEtsyApi =  etsyApiAdapter.create(EtsyApi.class);

    }



    @Override
    public Observable<List<EtsyProduct>> getItems(String category, String keywords, int offset) {

        if(mRateList == null) {

            mRateList = mCurrencyDownloader.getRateList();
            //return mEtsyApi.getItems(category, keywords, offset);
        }

        return mEtsyApi.getItems(category, keywords, offset)
                .flatMap(etsyProductList -> Observable.from(etsyProductList))
                .doOnNext(etsyProduct -> etsyProduct.setConvertedPrice(convert(etsyProduct.getCurrency(), etsyProduct.getPrice())))
                .toList();
    }

    private float convert(String currency, Float price) {
        return round(price / mRateList.getConversionRate(currency), 2);
    }

    public float round(float value, int places) {
        if (places < 0) throw new IllegalArgumentException();

        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(places, RoundingMode.HALF_UP);
        return bd.floatValue();
    }

    public void onEvent(RetrofitEvent event) {
        mRateList = mCurrencyDownloader.getRateList();
    }

}

@@ -155,18 +155,62 @@
 %0Aimport 
-de
+org.greenrobot.eventbus.Subscribe;%0A%0Aimport org
 .greenro
@@ -218,16 +218,19 @@
 ot.event
+bus
 .EventBu
@@ -1273,16 +1273,17 @@
 itory %7B%0A
+%0A
     priv
@@ -3788,32 +3788,47 @@
 Value();%0A    %7D%0A%0A
+    @Subscribe%0A
     public void 

Add @Subscribe as required by EventBus 3