package no.dnt.sjekkut.network;

import android.support.annotation.CallSuper;

import java.util.List;

import io.realm.Realm;
import no.dnt.sjekkut.pojo.PlaceList;
import no.dnt.sjekkut.realmmodels.Place;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;



public abstract class StorePlacesCallback implements Callback<PlaceList> {

    @CallSuper
    @Override
    public void onResponse(Call<PlaceList> call, Response<PlaceList> response) {
        if (response.isSuccessful()) {
            final List<Place> places = response.body().documents;
            Realm realm = Realm.getDefaultInstance();
            realm.executeTransactionAsync(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    for (Place place : places) {
                        Place realmPlace = realm.where(Place.class).equalTo("id", place.getId()).findFirst();
                        if (realmPlace == null || !realmPlace.isFullVersion()) {
                            realm.copyToRealmOrUpdate(place);
                        }
                    }
                }
            });
            realm.close();
        }
    }

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

    }
}
