package com.zhuinden.xkcdexample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import java.io.IOException;
import java.util.concurrent.Executor;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnLongClick;
import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmResults;
import retrofit2.Response;

public class MainActivity
        extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    @BindView(R.id.xkcd_image)
    ImageView image;

    @OnClick(R.id.xkcd_previous)
    public void previous() {
        if(!isDownloading && current != 0) {
            current--;
            downloadCurrent();
        }
    }

    @OnClick(R.id.xkcd_next)
    public void next() {
        if(!isDownloading && current < max) {
            current++;
            downloadCurrent();
        }
    }

    @SuppressWarnings("NewApi")
    private void downloadCurrent() {
        executor.execute(() -> {
            try {
                isDownloading = true;
                Response<XkcdResponse> _xkcdResponse = xkcdService.getNumber(current).execute();
                XkcdResponse xkcdResponse = _xkcdResponse.body();
                XkcdComic xkcdComic = xkcdMapper.from(xkcdResponse);
                try(Realm r = Realm.getDefaultInstance()) {
                    r.executeTransaction(realm -> realm.insertOrUpdate(xkcdComic));
                    current = xkcdComic.getNum();
                    max = xkcdComic.getNum();
                }
            } catch(IOException e) {
                Log.e(TAG, "Could not download XKCD data", e);
            } finally {
                isDownloading = false;
            }
        });
    }

    @OnLongClick(R.id.xkcd_image)
    public boolean longClickImage() {
        if(xkcdComic != null) {
            Toast.makeText(this, xkcdComic.getAlt(), Toast.LENGTH_LONG).show();
        }
        return true;
    }

    volatile boolean isDownloading = false;

    XkcdMapper xkcdMapper;
    XkcdService xkcdService;
    Executor executor;

    volatile int current = 0;

    volatile int max = 0;

    Realm realm;

    RealmResults<XkcdComic> results;
    XkcdComic xkcdComic;

    RealmChangeListener<RealmResults<XkcdComic>> realmChangeListener = element -> {
        if(!realm.isClosed()) {
            xkcdComic = getCurrentXkcdComic();
            if(xkcdComic != null) {
                updateUi(xkcdComic);
            }
        }
    };

    private XkcdComic getCurrentXkcdComic() {
        return realm.where(XkcdComic.class).equalTo(XkcdComicFields.NUM, current).findFirst();
    }

    private void updateUi(XkcdComic xkcdComic) {
        getSupportActionBar().setTitle(xkcdComic.getTitle());
        Glide.with(this).load(xkcdComic.getImg()).into(image);
    }

    @Override
    @SuppressWarnings("NewApi")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState != null) {
            current = savedInstanceState.getInt("current");
            max = savedInstanceState.getInt("max");
        }
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        realm = Realm.getDefaultInstance();
        results = realm.where(XkcdComic.class).findAll();
        results.addChangeListener(realmChangeListener);

        xkcdService = CustomApplication.get(this).xkcdService();
        xkcdMapper = CustomApplication.get(this).xkcdMapper();
        executor = CustomApplication.get(this).executor();

        xkcdComic = getCurrentXkcdComic();
        if(xkcdComic != null) {
            updateUi(xkcdComic);
        }
        if(current == 0) {
            executor.execute(() -> {
                try {
                    isDownloading = true;
                    Response<XkcdResponse> _xkcdResponse = xkcdService.getDefault().execute();
                    XkcdResponse xkcdResponse = _xkcdResponse.body();
                    XkcdComic xkcdComic = xkcdMapper.from(xkcdResponse);
                    try(Realm r = Realm.getDefaultInstance()) {
                        r.executeTransaction(realm -> realm.insertOrUpdate(xkcdComic));
                    }
                    current = xkcdComic.getNum();
                    max = xkcdComic.getNum();
                } catch(IOException e) {
                    Log.e(TAG, "Could not download XKCD data", e);
                } finally {
                    isDownloading = false;
                }
            });
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("current", current);
        outState.putInt("max", max);
    }

    @Override
    protected void onDestroy() {
        results.removeChangeListener(realmChangeListener);
        realm.close();
        realm = null;
        super.onDestroy();
    }
}

@@ -1305,32 +1305,379 @@
 cute();%0A        
+        handleXkcdResponse(_xkcdResponse);%0A            %7D catch(IOException e) %7B%0A                Log.e(TAG, %22Could not download XKCD data%22, e);%0A            %7D finally %7B%0A                isDownloading = false;%0A            %7D%0A        %7D);%0A    %7D%0A%0A    @SuppressWarnings(%22NewApi%22)%0A    private void handleXkcdResponse(Response%3CXkcdResponse%3E _xkcdResponse) %7B%0A
         XkcdResp
@@ -1714,32 +1714,24 @@
 nse.body();%0A
-        
         Xkcd
@@ -1783,32 +1783,24 @@
 e);%0A        
-        
 try(Realm r 
@@ -1827,32 +1827,24 @@
 stance()) %7B%0A
-        
             
@@ -1911,36 +1911,34 @@
 ));%0A        
-    
+%7D%0A
         
 current = xk
@@ -1917,32 +1917,35 @@
       %7D%0A        
+if(
 current = xkcdCo
@@ -1941,37 +1941,15 @@
 nt =
- xkcdComic.getNum();%0A        
+= 0) %7B%0A
     
@@ -1986,32 +1986,24 @@
 ();%0A        
-        
 %7D%0A          
@@ -2004,186 +2004,35 @@
     
-    %7D catch(IOException e) %7B%0A                Log.e(TAG, %22Could not download XKCD data%22, e);%0A            %7D finally %7B%0A                isDownloading = false;%0A            %7D%0A        %7D
+current = xkcdComic.getNum(
 );%0A 
@@ -4138,33 +4138,32 @@
 e%3CXkcdResponse%3E 
-_
 xkcdResponse = x
@@ -4221,398 +4221,39 @@
     
-XkcdResponse xkcdResponse = _xkcdResponse.body();%0A                    XkcdComic xkcdComic = xkcdMapper.from(xkcdResponse);%0A                    try(Realm r = Realm.getDefaultInstance()) %7B%0A                        r.executeTransaction(realm -%3E realm.insertOrUpdate(xkcdComic));%0A                    %7D%0A                    current = xkcdComic.getNum();%0A                    max = xkcdComic.getNum(
+handleXkcdResponse(xkcdResponse
 );%0A 

remove the bug + remove duplication