package it.feio.android.omninotes.async;

import it.feio.android.omninotes.DetailActivity;
import it.feio.android.omninotes.R;
import it.feio.android.omninotes.db.DbHelper;
import it.feio.android.omninotes.models.Attachment;
import it.feio.android.omninotes.models.Note;
import it.feio.android.omninotes.receiver.AlarmReceiver;
import it.feio.android.omninotes.utils.Constants;
import it.feio.android.omninotes.utils.StorageManager;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class SaveNoteTask extends AsyncTask<Note, Void, Note> {
	private final Activity mActivity;
	private boolean error = false;
	private boolean updateLastModification = true;

	public SaveNoteTask(Activity activity, boolean updateLastModification) {
		super();
		this.mActivity = activity;
		this.updateLastModification = updateLastModification;
	}

	@Override
	protected Note doInBackground(Note... params) {
		Note note = params[0];
		createAttachmentCopy(note);
		purgeRemovedAttachments(note);
		
		if (!error) {
			DbHelper db = new DbHelper(mActivity);		
			// Note updating on database
			note = db.updateNote(note, updateLastModification);
		} else {
			Toast.makeText(mActivity, mActivity.getString(R.string.error_saving_attachments), Toast.LENGTH_SHORT).show();
		}
			
		return note;
	}
	
	private void purgeRemovedAttachments(Note note) {
		ArrayList<Attachment> deletedAttachments = note.getAttachmentsListOld();
		for (Attachment attachment : note.getAttachmentsList()) {
			if (attachment.getId() != 0) {
				deletedAttachments.remove(attachment);
			}
		}
		// Remove from database deleted attachments
		for (Attachment deletedAttachment : deletedAttachments) {
			StorageManager.delete(mActivity, deletedAttachment.getUri().getPath());
		}
	}

	@Override
	protected void onPostExecute(Note note) {
		super.onPostExecute(note);
		
		// Set reminder if is not passed yet
		long now = Calendar.getInstance().getTimeInMillis();
		if (note.getAlarm() != null && Long.parseLong(note.getAlarm()) >= now) {
			setAlarm(note);
		}

		// Return back to parent activity now that the heavy work is done to speed up interface
		((DetailActivity)mActivity).goHome();
	}

	
	/**
	 * Makes copies of attachments files and replace uris 
	 * @param note
	 */
	private void createAttachmentCopy(Note note) {
		File destination;
		
		for (Attachment attachment : note.getAttachmentsList()) {
			
			if (attachment.getUri() == null) {
				error = true;
				return;
			}
				
			
			// The copy will be made only if it's a new attachment or if attachment directory is not yet the destination one
			if (attachment.getId() != 0 || 
					attachment.getUri().getPath().contains(mActivity.getExternalFilesDir(null).getAbsolutePath()))
				break;
			
			String extension = "";
			if (attachment.getMime_type().equals(Constants.MIME_TYPE_AUDIO))
				extension = Constants.MIME_TYPE_AUDIO_EXT;
			else if (attachment.getMime_type().equals(Constants.MIME_TYPE_IMAGE))
				extension = Constants.MIME_TYPE_IMAGE_EXT;
			else if (attachment.getMime_type().equals(Constants.MIME_TYPE_VIDEO))
				extension = Constants.MIME_TYPE_VIDEO_EXT;
								
			destination = StorageManager.createExternalStoragePrivateFile(mActivity, attachment.getUri(), extension);
			Log.v(Constants.TAG, "Moving attachment " + attachment.getUri() + " to " + destination);
			
			if (destination == null) {				
				Log.e(Constants.TAG, "Can't move file");
				break;
			}
			
			// Replace uri
			attachment.setUri(Uri.fromFile(destination));
		}
	}
	


	private void setAlarm(Note note) {
		Intent intent = new Intent(mActivity, AlarmReceiver.class);
		intent.putExtra(Constants.INTENT_NOTE, note);
		PendingIntent sender = PendingIntent.getBroadcast(mActivity, Constants.INTENT_ALARM_CODE, intent,
				PendingIntent.FLAG_CANCEL_CURRENT);
		AlarmManager am = (AlarmManager) mActivity.getSystemService(mActivity.ALARM_SERVICE);
		am.set(AlarmManager.RTC_WAKEUP, Long.parseLong(note.getAlarm()), sender);
	}
	
	
	
	
	
}

@@ -448,16 +448,52 @@
 o.File;%0A
+import java.lang.ref.WeakReference;%0A
 import j
@@ -854,24 +854,38 @@
 e final 
+WeakReference%3C
 Activity
  mActivi
@@ -876,16 +876,17 @@
 Activity
+%3E
  mActivi
@@ -1057,21 +1057,16 @@
 er();%0A%09%09
-this.
 mActivit
@@ -1069,24 +1069,53 @@
 ivity = 
-activity
+new WeakReference%3CActivity%3E(activity)
 ;%0A%09%09this
@@ -1374,16 +1374,22 @@
 Activity
+.get()
 );%09%09%0A%09%09%09
@@ -1510,16 +1510,22 @@
 Activity
+.get()
 , mActiv
@@ -1524,24 +1524,30 @@
 , mActivity.
+get().
 getString(R.
@@ -2048,16 +2048,22 @@
 Activity
+.get()
 , delete
@@ -2500,16 +2500,22 @@
 Activity
+.get()
 ).goHome
@@ -3028,16 +3028,22 @@
 ctivity.
+get().
 getExter
@@ -3559,16 +3559,22 @@
 Activity
+.get()
 , attach
@@ -3947,16 +3947,22 @@
 Activity
+.get()
 , AlarmR
@@ -4086,16 +4086,22 @@
 Activity
+.get()
 , Consta
@@ -4216,16 +4216,22 @@
 ctivity.
+get().
 getSyste
@@ -4249,16 +4249,22 @@
 ctivity.
+get().
 ALARM_SE

Should have fixed java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState at it.feio.android.omninotes.DetailActivity.goHome(DetailActivity.java:854) at it.feio.android.omninotes.async.SaveNoteTask.onPostExecute(SaveNoteTask.java:77)