/* 
 * Copyright 2015 by AVM GmbH <info@avm.de>
 *
 * This software contains free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License ("License") as 
 * published by the Free Software Foundation  (version 3 of the License). 
 * This software 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 copy of the 
 * License you received along with this software for more details.
 */

package de.avm.android.fritzapp.gui;

import de.avm.android.fritzapp.R;
import de.avm.android.fritzapp.util.ResourceHelper;
import de.avm.fundamentals.logger.FileLog;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;

/**
 * Activity to export LocalContacts as E-Mail
 */
public class LocalContactsExportActivity extends Activity
{
    private static final String TAG = "LocalContactsExportActivity";
	private static final String SAVED_LOADING = "loading";

	private SendLocalContactsTask mSendTask = null;
	private Object mToRetain = null;
	private WaitDialog mWaitDialog = null;
	private boolean mLoadOnResume = true;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.phonebook);
        ResourceHelper.setTitle(this, R.string.contacts_label);

    	Object retained = getLastNonConfigurationInstance();
    	if (SendLocalContactsTask.class.equals(retained) &&
    			(((SendLocalContactsTask)retained).getStatus() != AsyncTask.Status.FINISHED))
    	{
    		mSendTask = (SendLocalContactsTask)retained;
    		showWait();
    	}
    	if (savedInstanceState != null)
			mLoadOnResume = savedInstanceState.getBoolean(SAVED_LOADING);
	}
	
	protected void onSaveInstanceState(Bundle outState)
	{
		outState.putBoolean(SAVED_LOADING, mSendTask != null);
		mToRetain = mSendTask;
	}

    public Object onRetainNonConfigurationInstance()
    {
    	return mToRetain;
    }
	
	@Override
	protected void onNewIntent(Intent intent)
	{
		setIntent(intent);
		dismissWait();
		mSendTask = null;
		mLoadOnResume = true;
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		
		if (mLoadOnResume)
		{
			mToRetain = null;
			mLoadOnResume = false;
			startSending();
		}
		else finish(); // nothing to do
	}

	@Override
	protected void onPause()
	{
		super.onPause();
		dismissWait();
		mSendTask = null;
	}

	private void showWait()
	{
		if (mWaitDialog == null)
		{
			mWaitDialog = WaitDialog.show(this, R.string.wait_dialog,
					new DialogInterface.OnCancelListener()
			{
				public void onCancel(DialogInterface dialog)
				{
					if (dialog == mWaitDialog)
					{
						// cancel pending load
						mWaitDialog = null;
						dialog.dismiss();
						mSendTask = null;
						LocalContactsExportActivity.this.finish();
					}
					else dialog.dismiss();
				}
			});
		}
	}
	
	private void dismissWait()
	{
		if (mWaitDialog != null)
		{
			mWaitDialog.dismiss();
			mWaitDialog = null;
		}
	}
	
	private void startSending()
	{
		if (mSendTask == null)
		{
			showWait();
			mSendTask = (SendLocalContactsTask)new SendLocalContactsTask(this)
			{
				@Override
				protected void onPostExecute(Integer error)
				{
					super.onPostExecute(error);

					if (mSendTask == this)
					{
						dismissWait();
						mSendTask = null;
					
						String filePath = super.getExportFilePath();
						if (!TextUtils.isEmpty(filePath))
						{
							// TODO store filePath to remove export files later (don't delete too early!)
						}
						
						if (error.intValue() == 0)
						{
							try
							{
								LocalContactsExportActivity.this
										.startActivity(getSendIntent());
							}
							catch (ActivityNotFoundException e)
							{
                                FileLog.w(TAG, e.getMessage(), e);
								error = Integer.valueOf(
										R.string.contacts_send_error_emailclient);
							}
						}
	
						if (error.intValue() != 0)
						{
							try
							{
								TextDialog.createOk(LocalContactsExportActivity.this,
										LocalContactsExportActivity.this
										.getString(error.intValue()))
										.setPositiveButton(android.R.string.ok,
												new DialogInterface.OnClickListener()
										{
											public void onClick(DialogInterface dialog, int which)
											{
												finish();
											}
										}).show();
							}
							catch(Exception e)
							{
                                FileLog.w(TAG, e.getMessage(), e);
								finish();
							}
						}
						else finish();
					}
				}
			}.execute((Object)null);
		}
	}
}
