package eu.project.rapid.as.rest;

import android.content.Context;

import java.util.List;

import eu.project.rapid.as.BuildConfig;
import eu.project.rapid.as.bus.BusProvider;
import eu.project.rapid.as.dtos.DeviceDTO;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Talha on 4/3/2018.
 */

public class RestClient {

    //public static String BASE_URL = "https://thesis-central-server.herokuapp.com/";
    public static String BASE_URL = "http://192.168.0.100:8080/";
    private static RestClient ourInstance = new RestClient();
    private static ApiService apiService;

    private RestClient() {
    }

    public static RestClient getInstance(Context cxt) {

        if (apiService == null) {

            OkHttpClient.Builder builder = new OkHttpClient.Builder();

            if (BuildConfig.DEBUG) {
                HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
                interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                builder.addInterceptor(interceptor);
            }

            OkHttpClient client = builder.build();

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            apiService = retrofit.create(ApiService.class);
        }

        return ourInstance;
    }

    public ApiService getApiService() {
        return apiService;
    }

    public void getAllDevices() {

        Call<List<DeviceDTO>> call = getApiService().getAllDevices();

        call.enqueue(new Callback<List<DeviceDTO>>() {
            @Override
            public void onResponse(Call<List<DeviceDTO>> call, Response<List<DeviceDTO>> response) {
                BusProvider.getInstance().post(response.body());
            }

            @Override
            public void onFailure(Call<List<DeviceDTO>> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    public void updateDevice(DeviceDTO deviceDTO) {

        Call<DeviceDTO> call = getApiService().updateDevice(deviceDTO);

        call.enqueue(new Callback<DeviceDTO>() {
            @Override
            public void onResponse(Call<DeviceDTO> call, Response<DeviceDTO> response) {
                BusProvider.getInstance().post(response.body());
            }

            @Override
            public void onFailure(Call<DeviceDTO> call, Throwable t) {

            }
        });
    }

}
