package fi.reaktor.android.rx;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.squareup.okhttp.OkHttpClient;

import java.util.List;

import fi.reaktor.android.rx.jackson.deser.TotallylazyModule;
import fi.reaktor.android.rx.json.ImageSearch;
import fi.reaktor.android.rx.observables.AppObservables;
import rx.Observable;
import rx.Subscription;
import rx.android.widget.WidgetObservable;
import rx.functions.Action1;

public class MainActivity extends Activity {

    private OkHttpClient okHttpClient = new OkHttpClient();
    private ObjectMapper objectMapper = new ObjectMapper();
    private Subscription picturesSubscription;
    private Subscription searchActionSubscription;
    private Subscription editingSearchTermBegunSubscription;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        objectMapper.registerModule(new TotallylazyModule());
    }

    @Override
    protected void onResume() {
        super.onResume();
        TextView searchTerm = (TextView) findViewById(R.id.searchTerm);
        Observable<String> inputs = AppObservables.inputs(searchTerm);

        // show progress bar when a new valid input is emitted from inputs
        searchActionSubscription = AppObservables.doWhenSearching(inputs, showProgressBar).subscribe();

        // XXX: this subscription will die on first error, for example missing network.
        // This should be improved e.g. by subscribing again in errorHandler
        // or using RxJava error handlers: https://github.com/ReactiveX/RxJava/wiki/Error-Handling-Operators
        picturesSubscription = AppObservables.pictures(inputs, okHttpClient, objectMapper).subscribe(resultHandler, errorHandler);
    }

    // shows progressbar when new search starts
    private Action1<String> showProgressBar = resp ->
            findViewById(R.id.progressBar).setVisibility(View.VISIBLE);

    // takes results of image search and creates adapter for listview based on the result
    private Action1<ImageSearch.ImageSearchResponse> resultHandler = parsed -> {
        final ListView resultList = (ListView) findViewById(R.id.results);

        TextView searchTerm = (TextView) findViewById(R.id.searchTerm);
        editingSearchTermBegunSubscription = WidgetObservable.text(searchTerm, false).take(1).subscribe(_a -> {
            resultList.setAlpha(0.3f);
            editingSearchTermBegunSubscription.unsubscribe();
        });
        resultList.setAlpha(1.0f);

        List<String> urlList = parsed.responseData.results.map(i -> i.url).toList();
        resultList.setAdapter(new ImageListAdapter(urlList, this));
        // hide progress bar when search completes
        findViewById(R.id.progressBar).setVisibility(View.INVISIBLE);
    };

    // logs errors. Could update UI to notify about error as well.
    private Action1<Throwable> errorHandler = t -> Log.e("MainActivity", "Couldn't load images", t);

    @Override
    protected void onPause() {
        picturesSubscription.unsubscribe();
        searchActionSubscription.unsubscribe();
        if (!editingSearchTermBegunSubscription.isUnsubscribed()) {
            editingSearchTermBegunSubscription.unsubscribe();
        }
        super.onPause();
    }
}

@@ -526,16 +526,53 @@
 iption;%0A
+import rx.android.app.AppObservable;%0A
 import r
@@ -634,16 +634,63 @@
 Action1;
+%0Aimport rx.subscriptions.CompositeSubscription;
 %0A%0Apublic
@@ -865,80 +865,39 @@
 ate 
-Subscription picturesSubscription;%0A    private Subscription searchAction
+CompositeSubscription composite
 Subs
@@ -931,38 +931,21 @@
 ription 
-editingSearchTermBegun
+alpha
 Subscrip
@@ -1398,16 +1398,76 @@
 hTerm);%0A
+        compositeSubscription = new CompositeSubscription();
 %0A       
@@ -1546,34 +1546,66 @@
     
-searchActionSubscription =
+compositeSubscription.add(AppObservable.bindActivity(this,
  App
@@ -1656,16 +1656,17 @@
 ressBar)
+)
 .subscri
@@ -1669,16 +1669,17 @@
 scribe()
+)
 ;%0A%0A     
@@ -1688,11 +1688,12 @@
  // 
-XXX
+TODO
 : th
@@ -1952,32 +1952,33 @@
 ors%0A        
-pictures
+composite
 Subscription
@@ -1977,18 +1977,53 @@
 cription
- =
+.add(AppObservable.bindActivity(this,
  AppObse
@@ -2074,16 +2074,17 @@
 tMapper)
+)
 .subscri
@@ -2114,16 +2114,17 @@
 Handler)
+)
 ;%0A    %7D%0A
@@ -2630,44 +2630,96 @@
     
-editingSearchTermBegunSubscription =
+resultList.setAlpha(1.0f);%0A%0A        alphaSubscription = AppObservable.bindActivity(this,
  Wid
@@ -2763,16 +2763,17 @@
 .take(1)
+)
 .subscri
@@ -2834,106 +2834,9 @@
     
-    editingSearchTermBegunSubscription.unsubscribe();%0A        %7D);%0A        resultList.setAlpha(1.0f
+%7D
 );%0A%0A
@@ -3343,194 +3343,102 @@
     
-picturesSubscription.unsubscribe();%0A        searchActionSubscription.unsubscribe();%0A        if (!editingSearchTermBegunSubscription.isUnsubscribed()) %7B%0A            editingSearchTermBegun
+compositeSubscription.unsubscribe();%0A        if(alphaSubscription != null) %7B%0A            alpha
 Subs

Use composition subscription