// 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
//

package my.lan.zooty.upwithphp;

import android.app.Activity;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.database.Cursor;
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 android.util.Log;

public class UpWithPhpActivity extends Activity
{
    String Tag="UpWithPhpActivity";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ((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)) {
            Log.i(Tag,"saw action send");
            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);
                String filename = parseUriToFilename(uri);
                Log.i(Tag,"got filename: " + filename);

                if (filename != null) {
                    SharedPreferences prefs =
                       PreferenceManager.getDefaultSharedPreferences(this);
                    String url = prefs.getString("upload_host_edit_key", "");
                    boolean downcase =
                       prefs.getBoolean("downcase_name_checkbox_key", true);
                    (new Thread(new UploadFileToPhp(url,
                                                    downcase,
                                                    filename))).run();
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // Summarize the current prefs and record in text area.
        SharedPreferences prefs =
           PreferenceManager.getDefaultSharedPreferences(this);
        String url = prefs.getString("upload_host_edit_key", "");
        boolean downcase = prefs.getBoolean("downcase_name_checkbox_key", true);
        if (url == "") {
           String msg = "Upload location not defined.";
        } else {
           String dc;
           if (downcase) {
              dc = "Convert filenames to lower case.";
           } else {
              dc = "Preserve filename case.";
           }
           String msg = "Upload to:\n" + url + "\n" + dc;
           ((TextView) findViewById(R.id.msg_area)).setText(msg);
        }
    }

    public String parseUriToFilename(Uri uri) {
        String selectedImagePath = null;
        String filemanagerPath = uri.getPath();

        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);

        if (cursor != null) {

            // Here you will get a null pointer if cursor is null
            // This can be if you used OI file manager for picking the media

            int column_index = cursor.getColumnIndexOrThrow(
                                         MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            selectedImagePath = cursor.getString(column_index);
        }

        if (selectedImagePath != null) {
            return selectedImagePath;
        } else if (filemanagerPath != null) {
            return filemanagerPath;
        }
        return null;
    }

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