// App for sending image files to a PHP file upload server. The idea is that
// if it is invoked from a "share" action, it just sends the damn file,
// if it is invoked as an app, it allows you to configure the server to
// send to.
//
// Code from: http://twigstechtips.blogspot.com/2011/10/android-sharing-images-or-files-through.html
//
// I had the exact same problems as described here:
// https://issues.apache.org/jira/browse/CB-2293
// So I added the code to disable keep alive to see if that would fix it.
// (and absurdly, it seems to have done the trick).

package my.lan.zooty.upwithphp;

import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.net.Uri;
import android.widget.Button;
import android.view.View;
import android.widget.TextView;
import android.preference.PreferenceManager;
import android.content.SharedPreferences;
import java.util.Set;
import android.app.ProgressDialog;
import android.util.Log;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.widget.Toast;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.app.AlertDialog.Builder;
import android.app.AlertDialog;
import java.util.List;

public class UpWithPhpActivity extends Activity
{
   String Tag="UpWithPhpActivity";
   ProgressWithoutNumbers pd = null;
   Thread uploadThread = null;
   List<String> ProfileNames;
   ArrayAdapter<String> adapter;

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState)
   {
      super.onCreate(savedInstanceState);
      System.setProperty("http.keepAlive", "false");
      setContentView(R.layout.main);

      Profiles p = new Profiles(this);
      ProfileNames = p.getAllProfiles();
      ListView plist = (ListView)findViewById(R.id.profile_list);
      plist.setTextFilterEnabled(false);
      adapter = new ArrayAdapter<String>(this, R.layout.list_profiles,
                                         ProfileNames);
      plist.setAdapter(adapter);

      plist.setOnItemClickListener(new OnItemClickListener() {
         public void onItemClick(AdapterView<?> parent, View view,
                                 int position, long id) {
            String pname = ((TextView) view).getText().toString();
            switchToProfile(pname);
         }
      });

      plist.setOnItemLongClickListener(new OnItemLongClickListener() {
         public boolean onItemLongClick(AdapterView<?> arg0, View view,
                                        int pos, long id) {
            String pname = ((TextView) view).getText().toString();
            doRemoveProfile(pname);
            return true;
         }
      }); 

      ((Button) findViewById(R.id.config_button)).setOnClickListener(
         new Button.OnClickListener() {
            @Override public void onClick(View v) {
               updatePhpPrefs();
            } });

      Log.i(Tag,"In onCreate");
      Intent intent = getIntent();
      Bundle extras = intent.getExtras();
      String action = intent.getAction();

      // if this is from the share menu
      if (Intent.ACTION_SEND.equals(action)) {

         // Dump info about extras to logcat so I can find out what I'm
         // not handling if something doesn't work.

         Log.i(Tag,"saw action send");
         Set<String> keys = extras.keySet();
         for (String key : keys) {
            Object o = extras.get(key);
            String typeName = o.getClass().getName();
            Log.i(Tag,"intent has extra " + key + " type " + typeName);
            if (typeName.compareTo("java.lang.String") == 0) {
               String keyVal = extras.getString(key);
               Log.i(Tag,"   string value is " + keyVal);
            }
         }
         SharedPreferences prefs =
            PreferenceManager.getDefaultSharedPreferences(this);
         String url = prefs.getString("upload_host_edit_key", "");
         String formData = prefs.getString("form_data_edit_key",
                   getResources().getString(R.string.form_data_default));
         if (extras.containsKey(Intent.EXTRA_STREAM)) {
            // Get resource path
            Log.i(Tag,"saw extra stream");
            Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
            Log.i(Tag,"got uri: " + uri);

            boolean downcase =
               prefs.getBoolean("downcase_name_checkbox_key", true);
            uploadThread = new Thread(new UploadFileToPhp(this,
                                  url,
                                  downcase,
                                  uri,
                                  null,
                                  formData));
            uploadThread.start();
         } else if (extras.containsKey(Intent.EXTRA_TEXT)) {
            Log.i(Tag,"saw extra text");
            String textVal = extras.getString(Intent.EXTRA_TEXT);
            uploadThread = new Thread(new UploadFileToPhp(this,
                                  url,
                                  false,
                                  null,
                                  textVal,
                                  formData));
            uploadThread.start();
         }
      }
   }

   @Override
   protected void onResume() {
      super.onResume();
      Log.i(Tag, "In onResume");
      // Summarize the current prefs and record in text area.
      SharedPreferences prefs =
         PreferenceManager.getDefaultSharedPreferences(this);
      Profiles perm = new Profiles(this);
      perm.saveProfile(prefs);
      Log.i(Tag, "In onResume, profile saved");
      updateProfileInfo(prefs);
   }

   void updatePhpPrefs() {
      Intent launchPreferencesIntent =
         new Intent().setClass(this, UpWithPhpPrefsActivity.class);
      startActivity(launchPreferencesIntent);
   }

   void doUploadStart(int totalUpdates, String uploadName) {
      Log.i(Tag,"calling ProgressWithoutNumbers.show");
      pd = new ProgressWithoutNumbers(this);
      pd.setMessage(uploadName);
      pd.setTitle(getResources().getString(R.string.msg_uploading));
      if (totalUpdates == 0) {
         pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
         pd.setIndeterminate(true);
      } else {
         pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
         pd.setMax(totalUpdates);
         pd.setProgress(0);
         pd.setIndeterminate(false);
      }
      pd.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
         new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                   if (uploadThread != null) {
                      Log.i(Tag,"calling uploadThread.interrupt()");
                      uploadThread.interrupt();
                   }
                }
             });
      pd.show();
      Log.i(Tag,"called ProgressWithoutNumbers.show");
   }

   void doUpdateProgress() {
      if (pd != null) {
         pd.incrementProgressBy(1);
      }
   }

   void doUploadComplete() {
      if (pd != null) {
         Log.i(Tag,"calling ProgressWithoutNumbers.dismiss");
         pd.dismiss();
         pd = null;
      }
      finish();
   }

   void doToast(String msg) {
      Toast.makeText(this,msg,Toast.LENGTH_LONG).show();
   }

   void switchToProfile(String profile_name) {
      SharedPreferences prefs =
            PreferenceManager.getDefaultSharedPreferences(this);
      Profiles perm = new Profiles(this);
      perm.loadProfile(prefs, profile_name);
      updateProfileInfo(prefs);
   }

   void doRemoveProfile(String profile_name) {
      SharedPreferences prefs =
            PreferenceManager.getDefaultSharedPreferences(this);
      String cur_profile = prefs.getString("profile_name_edit_key",
                getResources().getString(R.string.profile_name_default_value));
      if (cur_profile.equals(profile_name)) {
         // Avoid dealing with deletion of current profile by simply
         // not allowing it.
         String msg = "Cannot delete current profile " + profile_name;
         new AlertDialog.Builder(this)
            .setTitle("Delete Error")
            .setMessage(msg)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int which) { 
                  // do nothing
               }
            }).show();
      } else {
         // Ask for confirmation of deletion.
         final String pname = profile_name;
         String msg = "Really delete profile " + profile_name + "?";
         new AlertDialog.Builder(this)
            .setTitle("Delete Profile")
            .setMessage(msg)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int which) { 
                  // continue with delete
                  removeProfile(pname);
               }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { 
               // do nothing
            }
            }).show();
      }
   }

   void removeProfile(String profile_name) {
      Profiles perm = new Profiles(this);
      perm.removeProfile(profile_name);
      SharedPreferences prefs =
            PreferenceManager.getDefaultSharedPreferences(this);
      updateProfileInfo(prefs);
   }

   void updateProfileInfo(SharedPreferences prefs) {
      adapter.clear();
      Profiles perm = new Profiles(this);
      ProfileNames = perm.getAllProfiles();
      adapter = new ArrayAdapter<String>(this, R.layout.list_profiles,
                                         ProfileNames);
      ListView plist = (ListView)findViewById(R.id.profile_list);
      plist.setAdapter(adapter);
      String url = prefs.getString("upload_host_edit_key", "");
      boolean downcase = prefs.getBoolean("downcase_name_checkbox_key", true);
      String msg = getResources().getString(R.string.msg_header);
      msg = msg + " " + prefs.getString("profile_name_edit_key",
               getResources().getString(R.string.profile_name_default_value));
      msg = msg + "\n";
      if (url == "") {
         url = getResources().getString(R.string.msg_no_host);
      }
      String dc;
      if (downcase) {
         dc = getResources().getString(R.string.downcase_name_checkbox_summary);
      } else {
         dc = getResources().getString(R.string.msg_keep_case);
      }
      msg = msg + getResources().getString(R.string.msg_upload_to) +
                     " " + url + "\n" + dc + "\n\n";
      msg = msg + getResources().getString(R.string.msg_footer);
      ((TextView) findViewById(R.id.msg_area)).setText(msg);
   }
}
