// 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.phpshare;

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.util.Log;

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

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        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) {
                    (new Thread(new UploadFileToPhp("http://zooty.my.lan/uploader.php",
                                                   filename))).run();
                }
            }
        }
        setContentView(R.layout.main);
    }

    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;
    }
}
