package no.dnt.sjekkut.network;

import android.app.IntentService;
import android.content.Intent;

import io.realm.Realm;
import io.realm.RealmResults;
import no.dnt.sjekkut.Extras;
import no.dnt.sjekkut.PreferenceUtils;
import no.dnt.sjekkut.Utils;
import no.dnt.sjekkut.realmmodels.Place;

public class OfflineMapsService extends IntentService {
    public static final String OFFLINE_MAP_FOR_PLACE = "OFFLINE_MAP_FOR_PLACE";

    public OfflineMapsService() {
        super("OfflineMapsService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null && OFFLINE_MAP_FOR_PLACE.equals(intent.getAction()) && intent.hasExtra(Extras.PLACE_ID)) {
            String placeId = intent.getStringExtra(Extras.PLACE_ID);
            if (Utils.isConnected(this) && PreferenceUtils.hasUserId(this) && placeId != null && !placeId.isEmpty()) {
                Realm realm = Realm.getDefaultInstance();
                RealmResults<Place> places = Place.findAll(realm, placeId);
                if (!places.isEmpty()) {
                    OfflineHelper.offlineMap(realm.copyFromRealm(places.subList(0, 1)));
                }
                realm.close();
            }
        }
    }
}

