package com.eaze.locationbackgroundtimer.track;

import android.location.Location;

import com.eaze.locationbackgroundtimer.BuildConfig;
import com.eaze.locationbackgroundtimer.LocationTimerService;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.Callback;

public class PostLocationServiceManager {
    private static PostLocationServiceManager sInstance = new PostLocationServiceManager();
    private PostLocationService mService;

    public String getBaseUrl() {
	return BuildConfig.BASE_API_URL;
    }

    public static PostLocationServiceManager get() {
        return sInstance;
    }

    private PostLocationServiceManager() {
        // Instantiate the Retrofit object for HTTP calls
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = BuildConfig.DEBUG_BUILD
                ? new OkHttpClient.Builder().addInterceptor(interceptor).build()
                : new OkHttpClient.Builder().build();

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

        mService = retrofit.create(PostLocationService.class);
    }

    public void postLocation(String token, Location location, final Callback<PostLocationResponse> callback) {
        PostLocationRequest request = new PostLocationRequest();
        request.latitude = location.getLatitude();
        request.longitude = location.getLongitude();
        request.recordedtime = LocationTimerService.getNowAsIso8601();
        Call<PostLocationResponse> call = mService.postLocation(token, request);
        call.enqueue(callback);
    }
}
