package com.github.klondike.android.campfire;

import java.io.FileNotFoundException;
import java.io.InputStream;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;
import android.widget.Toast;

import com.github.klondike.java.campfire.Campfire;
import com.github.klondike.java.campfire.CampfireException;
import com.github.klondike.java.campfire.Room;

public class ShareImage extends Activity {
	private static final int UPLOADING = 0;
	private static final int RESULT_ROOM_ID = 0;
	
	private Campfire campfire;
	private Room room;
	
	private boolean uploaded;
	private String uploadError;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		verifyLogin();
	}
	
	// guaranteed to be logged in and the "campfire" variable set
	public void onLogin() {
		loadRoom();
	}
	
	// guaranteed to have a room selected and the "room" variable set
	public void onLoadRoom() {
		uploadImage();
	}
	
	public void onUploadImage() {
		if (uploaded)
			alert("Uploaded image to Campfire.");
		else
			alert(uploadError);
		finish();
	}
	
	final Handler handler = new Handler();
	final Runnable afterUpload = new Runnable() {
		public void run() {
			dismissDialog(UPLOADING);
			onUploadImage();
		}
	};
	
	public void uploadImage() {
		Thread uploadThread = new Thread() {
			public void run() {
				try {
					Uri uri = (Uri) getIntent().getExtras().get("android.intent.extra.STREAM");
					
					InputStream stream = getContentResolver().openInputStream(uri);
					String mimeType = getContentResolver().getType(uri);
					String filename = filenameFor(mimeType);
					
					if (stream == null) {
						uploaded = false;
						uploadError = "Error processing photo, image was not uploaded.";
					} else {
						if (room.uploadImage(stream, filename, mimeType))
							uploaded = true;
						else {
							uploaded = false;
							uploadError = "Couldn't upload file to Campfire.";
						}
					}
				} catch (FileNotFoundException e) {
					uploaded = false;
					uploadError = "Error processing photo, image was not uploaded.";
				} catch (CampfireException e) {
					uploaded = false;
					uploadError = "Error connecting to Campfire, image was not uploaded.";
				}
				handler.post(afterUpload);
			}
		};
		uploadThread.start();
		
		showDialog(UPLOADING);
	}
	
	public void verifyLogin() {
    	campfire = Login.getCampfire(this);
        if (campfire != null)
        	onLogin();
        else
        	startActivityForResult(new Intent(this, Login.class), Login.RESULT_LOGIN);
    }
	
	public void loadRoom() {
		Intent intent = new Intent(this, RoomList.class);
		intent.putExtra("for_result", true);
		startActivityForResult(intent, RESULT_ROOM_ID);
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	switch (requestCode) {
    	case Login.RESULT_LOGIN:
    		if (resultCode == RESULT_OK) {
    			alert("You have been logged in successfully.");
    			campfire = Login.getCampfire(this);
    			onLogin();
    		} else
    			finish();
    		break;
    	case RESULT_ROOM_ID:
			if (resultCode == RESULT_OK) {
				String roomId = data.getExtras().getString("room_id");
				room = new Room(campfire, roomId);
				onLoadRoom();
			} else
				finish();
			break;
    	}
    }
	
	protected Dialog onCreateDialog(int id) {
        switch(id) {
        case UPLOADING:
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.setMessage("Uploading image...");
            return dialog;
        default:
            return null;
        }
    }
	
	public void alert(String msg) {
		Toast.makeText(ShareImage.this, msg, Toast.LENGTH_SHORT).show();
	}
	
	public static String filenameFor(String mimeType) {
		String suffix;
		if (mimeType.equals("image/jpeg") || mimeType.equals("image/jpg"))
			suffix = "jpg";
		else
			suffix = "jpg";
		return "from_phone." + suffix;
	}
	
}

@@ -202,48 +202,8 @@
 og;%0A
-import android.content.ContentResolver;%0A
 impo
@@ -4022,62 +4022,74 @@
 %7B%0A%09%09
-String suffix;%0A%09%09if (
+// default to whatever was in the 2nd half of the 
 mime
-Type.equals(%22image/jpeg%22) %7C%7C 
+ type%0A%09%09if (
 mime
@@ -4113,16 +4113,17 @@
 e/jp
+e
 g%22))%0A%09%09%09
 suff
@@ -4122,50 +4122,41 @@
 %0A%09%09%09
-suffix = %22jpg%22;%0A%09%09else%0A%09%09%09suffix = %22jpg%22;%0A
+return %22from_phone.jpg%22;%0A%09%09else%0A%09
 %09%09re
@@ -4180,14 +4180,30 @@
 %22 + 
-suffix
+mimeType.split(%22/%22)%5B1%5D
 ;%0A%09%7D

Handle all major mime types