/*******************************************************************************
 * Copyright (c) 2009 Ferenc Hechler - ferenc_hechler@users.sourceforge.net
 * 
 * This file is part of AndroMaze
 *
 * AndroMaze is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation;
 * either version 2 of the License, or (at your option) any later version.
 * 
 * AndroMaze is distributed
 * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with the AndroMaze;
 * if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *  
 *******************************************************************************/
package de.hechler.andmaz;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * This class provides a basic demonstration of how to write an Android
 * activity. Inside of its window, it places a single view: an EditText that
 * displays and edits some internal text.
 */
public class AndroMazeEditorActivity extends Activity {

	private static final String TAG = "ANDMAZ";
	private static final int DIALOG_ENTERNAME_SAVE = 1;
	private static final int DIALOG_SELECT_LOAD = 2;
	private static final int DIALOG_SELECT_DELETE = 3;
	Button btSave;
	Button btLoad;
	Button btDelete;
	Button btTest;
	Button btEMail;
	Button btExit;
	
	EditText etLevelText;
	LevelSetManager mLsm;

	String mLevelSetName;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

		// create view from xml
        setContentView(R.layout.editor);

        // find buttons in view
        btSave = ((Button) findViewById(R.id.btSave));
        btLoad = ((Button) findViewById(R.id.btLoad));
        btDelete = ((Button) findViewById(R.id.btDelete));
        btTest = ((Button) findViewById(R.id.btTest));
        btEMail = ((Button) findViewById(R.id.btEMail));
        btExit = ((Button) findViewById(R.id.btExit));

        etLevelText = ((EditText) findViewById(R.id.etLevelText));
        
        // set actions for buttons
        btSave.setOnClickListener(SaveListener);
        btLoad.setOnClickListener(LoadListener);
        btDelete.setOnClickListener(DeleteListener);
        btTest.setOnClickListener(TestListener);
        btEMail.setOnClickListener(EMailListener);
        btExit.setOnClickListener(ExitListener);
        
        if (mLsm == null)
        	mLsm = new LevelSetManager(this);
        String levelText = 
    		"111111111111\n" +
    		"111111111111\n" +
    		"111111111111\n" +
    		"111111711111\n" +
    		"111111011111\n" +
    		"111111211111\n" +
    		"111111111111\n" +
    		"111111111111\n"
    		+"\n"+
			"111111111111\n" +
			"111111111111\n" +
			"111111121111\n" +
			"111111101111\n" +
			"111116001111\n" +
			"111111111111\n" +
			"111111111111\n" +
			"111111111111\n"
		;
        SimplePersistence persist = new SimplePersistence(this, "leveleditor");
        mLevelSetName = persist.getString("levelsetname", "edit");
        levelText = persist.getString("leveltext", levelText);
        etLevelText.setText(levelText);
        
        Intent intent = getIntent();
        if (intent != null) {
        	Log.i(TAG, "found intent");
        	if ("android.intent.action.VIEW".equals(intent.getAction())) {
//        		String rawName = intent.getDataString();
        		byte[] rawData = readUriContent(intent.getData());
        		if (rawData != null) {
        			String textData = new String(rawData).replaceAll("\\r\\n", "\n");
        			LevelSet ls = new LevelSet(textData, "edit");
        			mLevelSetName = ls.getName();
        			textData = textData.replaceFirst("STORE[:].*\\n *\\n", "");
        			etLevelText.setText(textData);
        		}
        	}
        }
        
    }

    private byte[] readUriContent(Uri uri) {
    	byte[] result = null;
    	try {
        	InputStream is = getContentResolver().openInputStream(uri);
        	int size = is.available();
        	result = new byte[size];
        	int pos = 0;
        	int cnt = is.read(result, pos, size-pos);
        	while (cnt > 0) {
        		pos += cnt;
            	cnt = is.read(result, pos, size-pos);
        	}
        	is.close();
    	}
    	catch (Exception e) {
    		Log.e(TAG, e.getMessage(), e);
    	}
    	return result;
    }
    
    
    OnClickListener TestListener = new OnClickListener() {
        public void onClick(View v) {
        	String levelText = etLevelText.getText().toString();
            SimplePersistence persist = new SimplePersistence(AndroMazeEditorActivity.this, "leveleditor");
            persist.putString("leveltext", levelText);
            persist.putString("levelsetname", mLevelSetName);
            persist.commit();
	    	Intent intent = new Intent(AndroMazeEditorActivity.this, AndroMazeLevelActivity.class);
	    	intent.putExtra(AndroMazeLevelActivity.EXTRA_LEVELSETTEXT, levelText);
        	startActivity(intent);
        }
    };
    
    OnClickListener SaveListener = new OnClickListener() {
        public void onClick(View v) {
        	showDialog(DIALOG_ENTERNAME_SAVE);
        }
    };
    
    OnClickListener LoadListener = new OnClickListener() {
        public void onClick(View v) {
        	showDialog(DIALOG_SELECT_LOAD);
        }
    };

    OnClickListener DeleteListener = new OnClickListener() {
        public void onClick(View v) {
        	showDialog(DIALOG_SELECT_DELETE);
        }
    };

    @Override
    protected Dialog onCreateDialog(int id) {
    	final String[] items = mLsm.getLevelsetNames();
        switch (id) {
        case DIALOG_ENTERNAME_SAVE:
	        LayoutInflater factory = LayoutInflater.from(this);
	        final View enternameView = factory.inflate(R.layout.dialog_save_entername, null);
			final EditText edName = (EditText)enternameView.findViewById(R.id.name_edit);
			edName.setText(mLevelSetName);
	        return new AlertDialog.Builder(this)
	            .setIcon(R.drawable.icon)
	            .setTitle("Save Level-Set")
	            .setView(enternameView)
	            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int whichButton) {
	            		mLevelSetName = edName.getText().toString();
	            		String levelsettext = etLevelText.getText().toString();
	            		LevelSet ls = new LevelSet(levelsettext, mLevelSetName);
	            		mLsm.store(ls);
	                }
	            })
	            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int whichButton) {
	                }
	            })
	            .create();
	    case DIALOG_SELECT_LOAD:
	        return new AlertDialog.Builder(this)
	            .setTitle("LevelSet selection")
	            .setItems(items, new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int which) {
	                    /* User clicked so do some stuff */
	                    String levelSetName = items[which].toLowerCase();
	                    LevelSet ls = mLsm.getLevelset(levelSetName);
	                    if (ls == null) {
	            	        Toast.makeText(AndroMazeEditorActivity.this, "Error loading level '"+levelSetName+"'!", Toast.LENGTH_SHORT).show();
	            	        mLsm.updateLevelsetList();
	                    }
	                    else {
		                    mLevelSetName = levelSetName;
		                    String levelsettext = ls.toString();
		                    levelsettext = levelsettext.replaceFirst("STORE[:].*\\n *\\n", "");
		                    etLevelText.setText(levelsettext);
	                    }
	                }
	            })
	            .create();
	    case DIALOG_SELECT_DELETE:
	        return new AlertDialog.Builder(this)
	            .setTitle("Select LevelSet to delete")
	            .setItems(items, new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int which) {
	                    /* User clicked so do some stuff */
	                    String levelSetName = items[which].toLowerCase();
	                    mLsm.deleteLevelset(levelSetName);
	                }
	            })
	            .create();
        }        
        return null;
    }
    
    
    OnClickListener EMailListener = new OnClickListener() {
        public void onClick(View v) {
        	Intent msg=new Intent(Intent.ACTION_SEND);
        	String[] recipients={"ferenc.hechler@googlemail.com"};
        	msg.putExtra(Intent.EXTRA_EMAIL, recipients);
        	msg.putExtra(Intent.EXTRA_TEXT, etLevelText.getText().toString());
        	msg.putExtra(Intent.EXTRA_SUBJECT, "AndroMaze Levelset");
        	String levelsettext = etLevelText.getText().toString();
        	levelsettext = "STORE:"+mLevelSetName+"\n\n"+levelsettext;
        	byte[] lvlData = levelsettext.getBytes();
        	try {
    	    	File root = Environment.getExternalStorageDirectory();
    			if (root != null) {
    				// attachment is only created if sdcard is inserted
    				File tmpFile = new File(root,"AndroMaze/levelset.andmaz");
    				tmpFile.getParentFile().mkdirs();
    	    		tmpFile.delete();
					writeData(tmpFile, lvlData);
					Uri uri = Uri.fromFile(tmpFile);
		        	msg.putExtra(Intent.EXTRA_STREAM, uri);
		        	msg.setType("application/andmaz");  
    	    	}
			} catch (IOException e) {
				Log.e(TAG, e.getMessage(), e);
			}
        	startActivity(Intent.createChooser(msg, "EMail AndroMaze Levelset.."));        	
        }

    };
	private void writeData(File f, byte[] buf) throws IOException {
		FileOutputStream fos = new FileOutputStream(f);
		fos.write(buf);
		fos.close();
	}
       
    OnClickListener ExitListener = new OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    };


    @Override
    protected void onStop() {
    	super.onStop();
        SimplePersistence persist = new SimplePersistence(this, "leveleditor");
        persist.putString("leveltext", etLevelText.getText().toString());
        persist.putString("levelsetname", mLevelSetName);
        persist.commit();
    }
}