/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.micode.notes.tool;

import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;

import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;


/**

备份工具类，单例模式
*/
public class BackupUtils {

// 日志标签
private static final String TAG = "BackupUtils";

// 单例实例
private static BackupUtils sInstance;

/**

获取单例实例
@param context 上下文
@return 单例实例
*/
public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) {
sInstance = new BackupUtils(context);
}
return sInstance;
}
/**

下面的状态表示备份或还原的状态
*/
// 当前SD卡未挂载
public static final int STATE_SD_CARD_UNMOUONTED = 0;
// 备份文件不存在
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
// 数据格式不正确，可能被其他程序改变
public static final int STATE_DATA_DESTROIED = 2;
// 运行时异常导致备份或还原失败
public static final int STATE_SYSTEM_ERROR = 3;
// 备份或还原成功
public static final int STATE_SUCCESS = 4;
// 文本导出对象
private TextExport mTextExport;

/**

私有构造方法
@param context 上下文
*/
private BackupUtils(Context context) {
mTextExport = new TextExport(context);
}
/**

判断外部存储是否可用
@return 外部存储是否可用
*/
private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
/**

导出到文本
@return 备份状态
*/
public int exportToText() {
return mTextExport.exportToText();
}
/**

获取导出文本文件名
@return 导出文本文件名
*/
public String getExportedTextFileName() {
return mTextExport.mFileName;
}
/**

获取导出文本文件目录
@return 导出文本文件目录
*/
public String getExportedTextFileDir() {
return mTextExport.mFileDirectory;
}
}
/**

Note应用中的文本导出类
*/
private static class TextExport {

// 定义查询Note时需要使用的列的名字
private static final String[] NOTE_PROJECTION = {
NoteColumns.ID,
NoteColumns.MODIFIED_DATE,
NoteColumns.SNIPPET,
NoteColumns.TYPE
};

// 定义查询结果中各列的索引
private static final int NOTE_COLUMN_ID = 0;
private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
private static final int NOTE_COLUMN_SNIPPET = 2;

// 定义查询Data时需要使用的列的名字
private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
DataColumns.DATA4,
};

// 定义查询结果中各列的索引
private static final int DATA_COLUMN_CONTENT = 0;
private static final int DATA_COLUMN_MIME_TYPE = 1;
private static final int DATA_COLUMN_CALL_DATE = 2;
private static final int DATA_COLUMN_PHONE_NUMBER = 4;

// 定义文本格式的数组
private final String [] TEXT_FORMAT;

// 相关变量
private Context mContext;
private String mFileName;
private String mFileDirectory;

/**

构造函数，初始化相关变量

@param context 应用上下文
*/
public TextExport(Context context) {
// 获取文本格式数组
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);

mContext = context;
mFileName = "";
mFileDirectory = "";

}

/**

获取文本格式数组中指定下标的元素
@param id 要获取元素的下标
@return 文本格式数组中指定下标的元素
*/
private String getFormat(int id) {
return TEXT_FORMAT[id];
}
/**

将指定id的文件夹及其子note导出为文本
@param folderId 要导出的文件夹的id
@param ps 输出文本的PrintStream
*/
private void exportFolderToText(String folderId, PrintStream ps) {
// 查询属于指定文件夹的note
Cursor notesCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
NoteColumns.PARENT_ID + "=?",
new String[] { folderId },
null);
if (notesCursor != null) {
if (notesCursor.moveToFirst()) {
do {
// 输出note的最后修改日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// 查询属于指定note的data
String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
} while (notesCursor.moveToNext());
}
notesCursor.close();
}
}

/**

将指定id的note导出为文本
@param noteId 要导出的note的id
@param ps 输出文本的PrintStream
*/
private void exportNoteToText(String noteId, PrintStream ps) {
Cursor dataCursor = mContext.getContentResolver().query(
Notes.CONTENT_DATA_URI,
DATA_PROJECTION,
DataColumns.NOTE_ID + "=?",
new String[] { noteId },
null);
if (dataCursor != null) {
if (dataCursor.moveToFirst()) {
do {
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
if (DataConstants.CALL_NOTE.equals(mimeType)) {
// 如果是Call Note，则输出电话号码、通话日期和附件位置
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT);

// 如果电话号码不为空，则输出
if (!TextUtils.isEmpty(phoneNumber)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
phoneNumber));
}
// 输出通话日期
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
.format(mContext.getString(R.string.format_datetime_mdhm),
callDate)));
// 如果附件位置不为空，则输出
if (!TextUtils.isEmpty(location)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
location));
}
} else if (DataConstants.NOTE.equals(mimeType)) {
// 如果是普通Note，则输出内容
String content = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(content)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
content));
}
}
} while (dataCursor.moveToNext());
}
dataCursor.close();
}
// 在不同note之间输出一个空行
try {
ps.write(new byte[] { Character.LINE_SEPARATOR, Character.LETTER_NUMBER });
} catch (IOException e) {
Log.e(TAG, e.toString());
}
}

/**

将所有note导出为文本

@return 导出状态
*/
public int exportToText() {
if (!externalStorageAvailable()) {
// 检查外部存储是否挂载，未挂载则返回错误
Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED;
}

// 获取输出流
PrintStream ps = getExportToTextPrintStream();
if (ps == null) {
Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR;
}

// 首先导出各个文件夹及其子note
Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
"(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
+ NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER,
null,
null);
if (folderCursor != null) {
if (folderCursor.moveToFirst()) {
do {
// 输出文件夹的名称
String folderName = "";
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
folderName = mContext.getString(R.string.call_record_folder_name);
} else {
folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
}
if (!TextUtils.isEmpty(folderName)) {
ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
}
String folderId = folderCursor.getString(NOTE_COLUMN_ID);
exportFolderToText(folderId, ps);
} while (folderCursor.moveToNext());
}
folderCursor.close();
}

// 导出Root文件夹中的note
Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID
+ "=0",
null,
null);
if (noteCursor != null) {
if (noteCursor.moveToFirst()) {
do {
// 输出note的最后修改日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// 查询属于指定note的data
String noteId = noteCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
} while (noteCursor.moveToNext());
}
noteCursor.close();
}

ps.close();

return STATE_SUCCESS;

}

/**

获取输出流，指向SD卡上的文件

@return 输出流PrintStream
*/
private PrintStream getExportToTextPrintStream() {
File file = generateFileMountedOnSDcard(
mContext,
R.string.file_path,
R.string.file_name_txt_format);
if (file == null) {
Log.e(TAG, "create file to exported failed");
return null;
}

mFileName = file.getName();
mFileDirectory = mContext.getString(R.string.file_path);
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream(file);
ps = new PrintStream(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (NullPointerException e) {
e.printStackTrace();
return null;
}
return ps;

}

}

/**

生成文本文件以存储导入的数据
*/
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
// 使用StringBuilder的效率更高
StringBuilder sb = new StringBuilder();
// 获取SD卡目录并添加文件路径
sb.append(Environment.getExternalStorageDirectory());
sb.append(context.getString(filePathResId));
// 创建目录
File filedir = new File(sb.toString());
// 添加文件名
sb.append(context.getString(
fileNameFormatResId,
DateFormat.format(context.getString(R.string.format_date_ymd),
System.currentTimeMillis())));
// 创建文件
File file = new File(sb.toString());

try {
// 判断目录是否存在，如不存在则创建该目录
if (!filedir.exists()) {
filedir.mkdir();
}
// 判断文件是否存在，如不存在则创建该文件
if (!file.exists()) {
file.createNewFile();
}
return file;
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;

}


