package apidez.com.databinding.viewmodel;

import android.databinding.BaseObservable;
import android.databinding.Bindable;
import android.databinding.ObservableArrayList;
import android.support.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import apidez.com.databinding.model.api.IPlacesApi;
import apidez.com.databinding.model.entity.Place;
import rx.Observable;

/**
 * Created by nongdenchet on 10/21/15.
 */
public class PlacesViewModel extends BaseObservable implements IPlacesViewModel {
    private IPlacesApi mPlacesApi;
    private final int TIME_OUT = 5;
    private final int RETRY = 3;
    private List<Place> allPlaces;

    // Observable property
    private ObservableArrayList<Place> mPlaces = new ObservableArrayList<>();

    public PlacesViewModel(@NonNull IPlacesApi placesApi) {
        mPlacesApi = placesApi;
    }

    /**
     * Return an Observable that emits the current places
     */
    @Bindable
    public ObservableArrayList<Place> getCurrentPlaces() {
        return mPlaces;
    }

    /**
     * Command fetching all places
     */
    @Override
    public Observable<Boolean> fetchAllPlaces() {
        return mPlacesApi.placesResult()
                .map(googleSearchResult -> {
                    allPlaces = googleSearchResult.results;
                    mPlaces.clear();
                    mPlaces.addAll(allPlaces);
                    return true;
                })
                .timeout(TIME_OUT, TimeUnit.SECONDS)
                .retry(RETRY);
    }

    /**
     * Command filtering places
     */
    @Override
    public void filterPlacesByType(String type) {
        mPlaces.clear();
        if (type.equalsIgnoreCase("all")) {
            mPlaces.addAll(allPlaces);
        } else {
            List<Place> newPlaces = new ArrayList<>();
            Observable.from(allPlaces)
                    .filter(place -> place.getTypes().contains(getApiType(type)))
                    .subscribe(newPlaces::add);
            mPlaces.addAll(newPlaces);
        }
    }

    /**
     * Helpers change type to api_type
     */
    private String getApiType(String type) {
        type = type.toLowerCase();
        switch (type) {
            case "theater":
                return "movie_theater";
            default:
                return type;
        }
    }
}

@@ -212,36 +212,8 @@
 l;%0A%0A
-import java.util.ArrayList;%0A
 impo
@@ -1776,63 +1776,8 @@
 e %7B%0A
-            List%3CPlace%3E newPlaces = new ArrayList%3C%3E();%0A
     
@@ -1924,19 +1924,17 @@
 bscribe(
-new
+m
 Places::
@@ -1943,47 +1943,8 @@
 d);%0A
-            mPlaces.addAll(newPlaces);%0A
     

refactor viewmodel