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.*;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;


public class UserDicImportExport extends AsyncTask<String, String, String[]>{
	private UserDictionaryToolsList mActivity;
	private String[]  mResultString;

	
	public UserDicImportExport(UserDictionaryToolsList activity) {
		mActivity  = activity;
	}
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		mActivity.createProgressDialog();
	}

	@Override
	protected String[] doInBackground(String... params)  {
		boolean result = false;
		mResultString = new String[2];
		if (params[0].equals("import")) {
			result = importUserDic(params[1], params[2], params[3]);
			if (true == result) {
				mResultString[0] = "true";
				mResultString[1] = mActivity.getString(R.string.dialog_import_dic_message_done);
			}
			else{
				mResultString[0] = "false";
				mResultString[1] = mActivity.getString(R.string.dialog_import_dic_message_failed);
			}
		}
		else{
			exportUserDic(params[1], params[2], params[3]);
		}
		return mResultString;
	}
	@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();
		if (null == fileSdCard) {
			return false;
		}
		File fileBase = createNicoWnnDirectory(fileSdCard);
		if (null == fileBase) {
			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 boolean exportUserDic(String file, String flash, String sd) {
		mResultString[0] = "true";
		mResultString[1] = mActivity.getString(R.string.dialog_export_dic_message_done);

		File fileSdCard = getExternalStorageDirectory();
		if (null == fileSdCard) {
			mResultString[0] = "false";
			mResultString[1] = mActivity.getString(R.string.dialog_export_dic_message_failed);
			return false;
		}
		File fileBase = createNicoWnnDirectory(fileSdCard);
		if (null == fileBase) {
			return false;
		}
		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) {
			mResultString[0] = "false";
			mResultString[1] = mActivity.getString(R.string.dialog_export_dic_message_failed);
			return false;
		} finally {
			//
		}
		// export learn dic
		File sFile = new File(flash);
		File dFile = new File(fileBase, sd);
		copyFile(dFile, sFile);
		return true;
	}
	/*************************************************************************************/
    /* 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 File createNicoWnnDirectory(File fileSdCard) {
		boolean result;
		File fileOld  = null;
		File fileNico = null;
		fileOld  = new File(fileSdCard, "OpenWnn");
		fileNico = new File(fileSdCard, "nicoWnn");
		if (fileOld.exists()) {
			result = fileOld.renameTo(fileNico);
			if (false == result) {
				mResultString[0] = "false";
				mResultString[1] = mActivity.getString(R.string.dialog_importexport_rendir_failed);
				return null;
			}
			return fileNico;
		}
		if (!fileNico.exists()) {
			if (!fileNico.mkdir()) {
				mResultString[0] = "false";
				mResultString[1] = mActivity.getString(R.string.dialog_export_dic_message_failed);
				return null;
			} // mkdir
		} // exists
		return fileNico;
	}
	/*
	 * 
	 */
	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 ******************************/
