package com.morihacky.android.rxjava;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import com.morihacky.android.rxjava.retrofit.GithubApi;
import com.morihacky.android.rxjava.retrofit.User;
import java.util.ArrayList;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import timber.log.Timber;

import static com.google.common.base.Strings.isNullOrEmpty;
import static java.lang.String.format;

public class RetrofitAsyncTaskDeathFragment
      extends Fragment {

    @InjectView(R.id.btn_demo_retrofit_async_death_username) EditText _username;
    @InjectView(R.id.log_list) ListView _resultList;

    private GithubApi _api;
    private ArrayAdapter<String> _adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        _api = _createGithubApi();
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        View layout = inflater.inflate(R.layout.fragment_retrofit_async_task_death,
              container,
              false);
        ButterKnife.inject(this, layout);

        _adapter = new ArrayAdapter<>(getActivity(),
              R.layout.item_log,
              R.id.item_log,
              new ArrayList<String>());
        //_adapter.setNotifyOnChange(true);
        _resultList.setAdapter(_adapter);

        return layout;
    }

    @OnClick(R.id.btn_demo_retrofit_async_death)
    public void onGetGithubUserClicked() {
        _adapter.clear();

        /*new AsyncTask<String, Void, User>() {

            @Override
            protected User doInBackground(String... params) {
                return _api.getUser(params[0]);
            }

            @Override
            protected void onPostExecute(User user) {
                _adapter.add(format("%s  = [%s: %s]", _username.getText(), user.name, user.email));
            }
        }.execute(_username.getText().toString());*/


        Observable.just(_username.getText().toString())
              .subscribeOn(Schedulers.io())
              .observeOn(AndroidSchedulers.mainThread())
              .flatMap(new Func1<String, Observable<User>>() {
                  @Override
                  public Observable<User> call(String username) {
                      return _api.user(username);
                  }
              })
              .subscribe(new Observer<User>() {
                  @Override
                  public void onCompleted() {
                  }

                  @Override
                  public void onError(Throwable e) {
                  }

                  @Override
                  public void onNext(User user) {
                      _adapter.add(format("%s  = [%s: %s]",
                            _username.getText(),
                            user.name,
                            user.email));
                  }
              });

    }

    // -----------------------------------------------------------------------------------

    private GithubApi _createGithubApi() {

        RestAdapter.Builder builder = new RestAdapter.Builder().setEndpoint(
              "https://api.github.com/");
        //.setLogLevel(RestAdapter.LogLevel.FULL);

        final String githubToken = getResources().getString(R.string.github_oauth_token);
        if (!isNullOrEmpty(githubToken)) {
            builder.setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestFacade request) {
                    request.addHeader("Authorization", format("token %s", githubToken));
                }
            });
        }

        return builder.build().create(GithubApi.class);
    }

    // -----------------------------------------------------------------------------------

    private class GetGithubUser
          extends AsyncTask<String, Void, User> {

        @Override
        protected User doInBackground(String... params) {
            return _api.getUser(params[0]);
        }

        @Override
        protected void onPostExecute(User user) {
            _adapter.add(format("%s  = [%s: %s]", _username.getText(), user.name, user.email));
        }
    }
}

@@ -2195,25 +2195,24 @@
 , User%3E() %7B%0A
-%0A
             
@@ -2590,25 +2590,24 @@
 ());*/%0A%0A
-%0A
         
 Observab
@@ -2602,23 +2602,17 @@
     
-Observable.just
+_api.user
 (_us
@@ -2745,252 +2745,8 @@
 ())%0A
-              .flatMap(new Func1%3CString, Observable%3CUser%3E%3E() %7B%0A                  @Override%0A                  public Observable%3CUser%3E call(String username) %7B%0A                      return _api.user(username);%0A                  %7D%0A              %7D)%0A
     
@@ -3266,32 +3266,32 @@
               %7D%0A
+
               %7D)
@@ -3292,17 +3292,16 @@
     %7D);%0A
-%0A
     %7D%0A%0A 

use Retrofit Observable return type directly