/* 
 * 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 java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;

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

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;

/**
 *	Task to send local contacts via E-Mail
 *	(Override void onPostExecute(Integer error) to get result
 *	and to start email intent)
 */
public class SendLocalContactsTask extends AsyncTask<Object, Integer, Integer>
{
    private static final String TAG = "SendLocalContactsTask";
	private final static String XML_PREFIX_FMT =
		"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
		"\n<phonebooks>\n<phonebook owner=\"1\" name=\"%s\">";
	private final static String XML_POSTFIX =
		"\n</phonebook>\n</phonebooks>";
	
	private Context mContext;
	private String mExportFilePath = null;
	private Intent mSendIntent = null;
	
	/**
	 * @return exported file after task completed
	 */
	public String getExportFilePath()
	{
		return mExportFilePath;
	}
	
	/**
	 * @return intent to send email after task completed
	 */
	public Intent getSendIntent()
	{
		return mSendIntent;
	}
	
	public SendLocalContactsTask(Context context)
	{
		mContext = context; 
	}

	@Override
	protected Integer doInBackground(Object... params)
	{
		BufferedWriter fileOut = null;
		WakeLock wakeLock = ((PowerManager)mContext
				.getSystemService(Context.POWER_SERVICE))
				.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,
						SendLocalContactsTask.class.getName());
		wakeLock.acquire();
		try
		{
			// export file
			if (!Environment.MEDIA_MOUNTED.equals(
					Environment.getExternalStorageState()))
				return R.string.contacts_send_error_sdcard;
			File fileExport = createExportFile();
			if (fileExport == null)
				return R.string.contacts_send_error_compose;
			
			// export contacts
			fileOut = new BufferedWriter(new FileWriter(fileExport, false));
			fileOut.append(String.format(XML_PREFIX_FMT,
					LocalContacts.encodeEntities(Build.MODEL)));
            LocalContacts localContacts = LocalContacts.getInstance();
            final BufferedWriter fileOut2 = fileOut; 
            localContacts.exportAllContacts(mContext,
            		new LocalContacts.OnExportContactListener()
			{
				public void onExportContact(String xmlFragment) throws Exception
				{
					fileOut2.append("\n" + xmlFragment);
				}
				
			});
			fileOut.append(XML_POSTFIX);
			
			// let the user send it via email
			composeEmail(Uri.parse(fileExport.toURI().toString()));
			return 0;
		}
		catch (ActivityNotFoundException e)
		{
            FileLog.w(TAG, e.getMessage(), e);
			return R.string.contacts_send_error_emailclient;
		}
		catch(Exception e)
		{
            FileLog.w(TAG, e.getMessage(), e);
			return R.string.contacts_send_error_compose;
		}
		finally
		{
			if (fileOut != null)
			{
				try { fileOut.close(); }
				catch (IOException e) { /*ignore*/ }
			}
			mContext = null;
			wakeLock.release();
		}
	}

	private File createExportFile() throws IOException
	{
		File directory = EnvironmentHelper.getExternalFilesDir(mContext);
		if (directory != null)
		{
			GregorianCalendar now = new GregorianCalendar();
			// ..."%s_%02d.%02d.%02d_%02d%02d"...
			File file = new File(directory, String.format(mContext
					.getString(R.string.contacts_send_filename_fmt),
					Build.MODEL, now.get(Calendar.DAY_OF_MONTH),
					now.get(Calendar.MONTH), now.get(Calendar.YEAR),
					now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE)));
			if (file.exists()) file.delete();
			if (file.createNewFile())
			{
				// delete it later
				mExportFilePath = file.getAbsolutePath();
				try { file.deleteOnExit(); }
				catch (Exception e) { /*ignore*/ }
				return file;
			}
		}
		return null;
	}
	
	private void composeEmail(Uri uri)
	{
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("message/rfc822");
		intent.putExtra(Intent.EXTRA_SUBJECT, mContext
				.getString(R.string.contacts_send_subject));
		intent.putExtra(Intent.EXTRA_TEXT, String.format(mContext
				.getString(R.string.contacts_send_body_fmt), Build.MODEL));
		intent.putExtra(Intent.EXTRA_STREAM, uri);
		mSendIntent = Intent.createChooser(intent, mContext
				.getString(R.string.contacts_send_title));
	}
}
