package com.hiroshica.android.input.nicownn2;

import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

import java.util.ArrayList;
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.FileOutputStream;
import java.io.*;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;




public class UserDicImportExport extends AsyncTask<String, String, String[]>{
	private UserDictionaryToolsList mActivity;
	
	public UserDicImportExport(UserDictionaryToolsList activity) {
		mActivity  = activity;
	}
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		mActivity.createProgressDialog();
	}

	@Override
	protected String[] doInBackground(String... params)  {
		boolean result = false;
		String[]  resultString = new String[2];
		if (params[0].equals("import")) {
			result = importUserDic(params[1], params[2], params[3]);
			if (true == result) {
				resultString[0] = "true";
				resultString[1] = mActivity.getString(R.string.dialog_import_dic_message_done);
			}
			else{
				resultString[0] = "false";
				resultString[1] = mActivity.getString(R.string.dialog_import_dic_message_failed);
			}
		}
		else{
			resultString = exportUserDic(params[1], params[2], params[3]);
			/*
			if (true == result) {
				resultString[0] = "true";
				resultString[1] = mActivity.getString(R.string.dialog_export_dic_message_done);
			}
			else{
				resultString[0] = "false";
				resultString[1] = mActivity.getString(R.string.dialog_export_dic_message_failed);
			}
			*/
		}
		return resultString;
	}
	@Override
	protected void onPostExecute(String[] result) {
		mActivity.removeProgressDialog(result);
	}
	@Override
	protected void onCancelled() {
		super.onCancelled();
	}

	/*
	 *
	 */
	private boolean importUserDic(String file, String sd, String flash) {
		File fileSdCard = getExternalStorageDirectory();
		File fileBase = null;
		if (fileSdCard != null) {
			//fileBase = new File(fileSdCard, mActivity.getPackageName());
			fileBase = new File(fileSdCard, "nicoWnn");
			if (!fileBase.exists()) {
				return false;
			}
		}
		// import learn dic
		File sFile = new File(fileBase, sd);
		File dFile = new File(flash);
		if (false == copyFile(dFile, sFile)) {
			return false;
		}
		Log.d("load", "finish import learn dic!!\n");

		ArrayList<WnnWord> importList = new ArrayList<WnnWord>();
		try {
			File fileLoad = new File(fileBase, file);
			Log.d("load", "create fileload\n");
			FileInputStream fin = new FileInputStream(fileLoad);
			Log.d("load", "create inputstream\n");
			final XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			final XmlPullParser parser = factory.newPullParser();
			parser.setInput(fin, "UTF8");
			Log.d("load", "create XML parser\n");
			int eventType;			
			String tagName;
			String tagText;
			for(eventType = parser.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = parser.next()){
				tagName = parser.getName();
				if (eventType != XmlPullParser.START_TAG)    continue;
				if (tagName == null)    continue;
				if (!tagName.equals("dicword"))    continue;
				// entry word
				WnnWord newword = new WnnWord();
				newword.stroke    = parser.getAttributeValue(null,"stroke").replaceAll("\"", "");
				Log.d("load", "get stroke = "+newword.stroke+"\n");
				do {
					eventType = parser.next();
					if (eventType == XmlPullParser.TEXT) {
						newword.candidate = parser.getText().replaceAll("\"", "");;
						Log.d("load", "get candidate = "+newword.candidate+"\n");
						break;
					}
				} while (eventType == XmlPullParser.END_DOCUMENT);
				if (eventType == XmlPullParser.END_DOCUMENT) {
					break;
				}
				importList.add(importList.size(), newword);
			}
		} catch (Exception e) {
			return false;
		} finally {
			//
		}
		// set new wordlist
		Log.d("load", "set new wordlist\n");
		int size = importList.size();
		for (int iI = 0; iI < size; ++iI) {
			WnnWord getword = importList.get(iI);
			boolean result = mActivity.addImportWord(getword);
			if (false == result) {
				return false;
			}
		}
		Log.d("load", "finish import!!\n");
		return true;
	}
	/*
	 *
	 */
	private String[] exportUserDic(String file, String flash, String sd) {
		String[] resultString = new String[2];
		resultString[0] = "true";
		resultString[1] = mActivity.getString(R.string.dialog_export_dic_message_done);

		File fileSdCard = getExternalStorageDirectory();
		File fileBase = null;
		if (fileSdCard != null) {
			//fileBase = new File(fileSdCard, mActivity.getPackageName());
			fileBase = new File(fileSdCard, "nicoWnn");
			if (!fileBase.exists()) {
				if (!fileBase.mkdir()) {
					resultString[0] = "false";
					resultString[1] = mActivity.getString(R.string.dialog_export_dic_message_failed);
					return resultString;
				} // mkdir
			} // exists
		} // sd card
		else{
			resultString[0] = "false";
			resultString[1] = mActivity.getString(R.string.dialog_export_dic_message_failed);
			return resultString;
		}
		try {
			File fileSave = new File(fileBase, file);
			FileOutputStream fout = new FileOutputStream(fileSave);
			// output XML header
			String header = new String("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
			String top    = new String("<wordlist>\n");
			String end    = new String("</wordlist>\n");

			fout.write(header.getBytes());
			fout.write(top.getBytes());
			// create data
			int size = mActivity.getWordListSize();
			WnnWord getword;
			for (int iI = 0; iI < size; ++iI) {
				getword = mActivity.getWnnWord(iI);
				String outstring = new String("  <dicword stroke=\"" + getword.stroke + "\">\"" + getword.candidate + "\"</dicword>\n");
				fout.write(outstring.getBytes());
			}
			fout.write(end.getBytes());
		} catch (Exception e) {
			resultString[0] = "false";
			resultString[1] = mActivity.getString(R.string.dialog_export_dic_message_failed);
			return resultString;
		} finally {
			//
		}
		// export learn dic
		File sFile = new File(flash);
		File dFile = new File(fileBase, sd);
		copyFile(dFile, sFile);
		return resultString;
	}
	/*************************************************************************************/
    /* file load/save                                                                    */
    /*************************************************************************************/
	/*
	 * 
	 */
	private File getExternalStorageDirectory() {
		boolean state = Environment.getExternalStorageState().contains(Environment.MEDIA_MOUNTED);
		if (false == state) {
			Log.d("sdcard", "not mount sdcard!!\n");
			return null;
		}
		Log.d("sdcard", "mount sdcard!!\n");
		return Environment.getExternalStorageDirectory();
	}
	private boolean copyFile(File dFile, File sFile) {
		if (!sFile.exists()) {
			return false;
		}
		InputStream input = null;
		OutputStream output = null;
		try {
			input  = new FileInputStream(sFile);
			output = new FileOutputStream(dFile);
			int DEFAULT_BUFFER_SIZE = 1024 * 4;
			byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
			int n = 0;
			while (-1 != (n = input.read(buffer))) {
				output.write(buffer, 0, n);
			}
			input.close();
			output.close();
		} catch (Exception e) {
			return false;
		}
		return true;
	}
}
/****************************** end of file ******************************/
