package edu.alaska.gina.feeder.puffinfeeder;

import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;

/**
 * Fragment containing WebView that displays full-sized image.
 * Created by bobby on 7/1/13.
 */
public class ImageViewerFragment extends SherlockFragment{
    protected String image_url_small;
    protected String image_url_med;
    protected String image_url_large;
    protected String title;
    protected WebView image_frame;
    protected SharedPreferences sharedPreferences;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_image_viewer, container, false);
        setHasOptionsMenu(true);
        return v;
    }

    @Override
    public void onStart() {
        super.onStart();

        image_frame = (WebView) getActivity().findViewById(R.id.fragment_feed_image_webview);
        image_frame.getSettings().setBuiltInZoomControls(true);
        image_frame.getSettings().setLoadWithOverviewMode(true);


        image_frame.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                try {
                    getSherlockActivity().setSupportProgress(newProgress * 100);
                    if (newProgress >= 0)
                        getSherlockActivity().setSupportProgressBarIndeterminate(false);
                    if (newProgress >= 100) {
                        getSherlockActivity().setSupportProgressBarVisibility(false);
                        getSherlockActivity().setSupportProgressBarIndeterminateVisibility(false);
                    }
                } catch (NullPointerException nXe) {
                    Log.d(getString(R.string.app_tag), "ProgressBar NullPointer!\n" + nXe.getStackTrace());
                }
            }
        });

        Bundle extra = getArguments();
        if (extra != null) {
            image_url_small = extra.getString("image_url_small");
            image_url_med = extra.getString("image_url_med");
            image_url_large = extra.getString("image_url_large");
            title = extra.getString("bar_title");
        }
        else {
            Log.d(getString(R.string.app_tag), "No Image URL. Please Fix that...");
            Toast.makeText(getActivity(), "No Image URL. Please fix that...", Toast.LENGTH_SHORT).show();
            return;
        }

        getSherlockActivity().getSupportActionBar().setTitle(title);

        getSherlockActivity().setSupportProgressBarVisibility(true);
        getSherlockActivity().setSupportProgressBarIndeterminate(true);
        getSherlockActivity().setSupportProgressBarIndeterminateVisibility(true);

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
        sharedPreferences.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
                loadme(pickLoadSize());
            }
        });

        loadme(pickLoadSize());
    }

    @Override
    public void onDetach() {
        super.onDetach();

        image_frame.destroy();
    }

    private boolean isMetered(NetworkInfo net1) {
        int type = net1.getType();
        switch (type) {
            case ConnectivityManager.TYPE_MOBILE:
            case ConnectivityManager.TYPE_MOBILE_DUN:
            case ConnectivityManager.TYPE_MOBILE_HIPRI:
            case ConnectivityManager.TYPE_MOBILE_MMS:
            case ConnectivityManager.TYPE_MOBILE_SUPL:
                return true;
            default:
                return false;
        }
    }

    private String pickLoadSize() {
        ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(getActivity().CONNECTIVITY_SERVICE);
        NetworkInfo nf = cm.getActiveNetworkInfo();

        if (nf != null) {
            if (sharedPreferences.getBoolean("pref_smart_sizing_on/off", true) && isMetered(nf))
                return sharedPreferences.getString("pref_smart_sizing_size", "small");
            else
                return sharedPreferences.getString("pref_viewer_image_size", "med");
        }
        else {
            Log.d(getString(R.string.app_tag), "NetworkInfo null!");
            return sharedPreferences.getString("pref_viewer_image_size", "med");
        }
    }

    private void loadme(String size) {
        if (size.equals("small"))
            image_frame.getSettings().setUseWideViewPort(false);
        else
            image_frame.getSettings().setUseWideViewPort(true);

        image_frame.stopLoading();
        image_frame.loadUrl(getImageUrl(size));
    }

    private String getImageUrl(String sizeString) {
        if (sizeString.equals("small"))
            return image_url_small;
        if (sizeString.equals("med"))
            return image_url_med;
        if (sizeString.equals("large"))
            return image_url_large;

        return null;
    }
}

@@ -880,16 +880,71 @@
 erences;
+%0A    protected ConnectivityManager connectivityManager;
 %0A%0A    @O
@@ -1490,16 +1490,72 @@
 true);%0A%0A
+        connectivityManager = getConnectivityManager();%0A
 %0A       
@@ -2240,18 +2240,16 @@
 ception 
-nX
 e) %7B%0A   
@@ -2335,10 +2335,8 @@
 %22 + 
-nX
 e.ge
@@ -3605,24 +3605,51 @@
 String s) %7B%0A
+            if (isAdded())%0A
             
@@ -3695,32 +3695,59 @@
  %7D%0A        %7D);%0A%0A
+        if (isAdded())%0A    
         loadme(p
@@ -3758,24 +3758,24 @@
 oadSize());%0A
-
     %7D%0A%0A    @
@@ -3834,25 +3834,24 @@
 onDetach();%0A
-%0A
         imag
@@ -4395,17 +4395,17 @@
         
-C
+c
 onnectiv
@@ -4419,14 +4419,13 @@
 ger 
-cm = (
+= get
 Conn
@@ -4443,75 +4443,9 @@
 ager
-) getActivity().getSystemService(getActivity().CONNECTIVITY_SERVICE
+(
 );%0A 
@@ -4469,17 +4469,34 @@
 o nf = c
-m
+onnectivityManager
 .getActi
@@ -5600,16 +5600,16 @@
 large;%0A%0A
-
         
@@ -5626,11 +5626,250 @@
 l;%0A    %7D
+%0A%0A    private ConnectivityManager getConnectivityManager() %7B%0A        if (isAdded())%0A            return (ConnectivityManager) getActivity().getSystemService(getActivity().CONNECTIVITY_SERVICE);%0A        return this.connectivityManager;%0A    %7D
 %0A%7D%0A

Fix Issue #7.