/*
 * 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";
    // Singleton stuff
    private static BackupUtils sInstance;
    /*获取BackupUtils的单例实例（线程安全）
    这是一个同步方法，确保在多线程环境下只会创建一个BackupUtils实例。*/
    public static synchronized BackupUtils getInstance(Context context) {
        //检查静态实例是否已初始化
        if (sInstance == null) {
            //若未初始化，则创建新实例
            sInstance = new BackupUtils(context);
        }
        //返回单例实例
        return sInstance;
    }

    /**
     * Following states are signs to represents backup or restore
     * status
     */
    // 当前未挂载该sd卡
    public static final int STATE_SD_CARD_UNMOUONTED           = 0;
    // The backup file not exist
    public static final int STATE_BACKUP_FILE_NOT_EXIST        = 1;
    // The data is not well formated, may be changed by other programs
    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;

    private BackupUtils(Context context) {
        mTextExport = new TextExport(context);
    }
    //获取可用外部存储
    private static boolean externalStorageAvailable() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    public int exportToText() {
        return mTextExport.exportToText();
    }
    //获取文件夹名字
    public String getExportedTextFileName() {
        return mTextExport.mFileName;
    }
    //获取文件夹目录
    public String getExportedTextFileDir() {
        return mTextExport.mFileDirectory;
    }

    private static class TextExport {
        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;
        //定义查询笔记数据时需要的列名数组（数据表的列投影）
        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 static final int FORMAT_FOLDER_NAME          = 0;
        private static final int FORMAT_NOTE_DATE            = 1;
        private static final int FORMAT_NOTE_CONTENT         = 2;

        private Context mContext;
        private String mFileName;
        private String mFileDirectory;

        public TextExport(Context context) {
            TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
            mContext = context;
            mFileName = "";
            mFileDirectory = "";
        }

        private String getFormat(int id) {
            return TEXT_FORMAT[id];
        }

        /**
         * 将文件夹id标识的文件夹导出为文本
         */
        private void exportFolderToText(String folderId, PrintStream ps) {
            // 查询属于当前文件夹的所有笔记
            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 {
                        // 打印笔记的最后修改日期（格式化为“月-日 时：分”格式）
                        ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
                                mContext.getString(R.string.format_datetime_mdhm),
                                notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
                        // 获取当前笔记ID
                        String noteId = notesCursor.getString(NOTE_COLUMN_ID);
                        //导出笔记内容到文本
                        exportNoteToText(noteId, ps);
                    }
                    //处理下一条笔记
                    while (notesCursor.moveToNext());
                }
                //关闭游标释放资源
                notesCursor.close();
            }
        }

        /**
         * 将笔记内容导出为文本格式
         */
        private void exportNoteToText(String noteId, PrintStream ps) {
            //查询指定noteId的所有数据项
            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 {
                        //获取当前记录的MIME类型
                        String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
                        //处理通话记录类型的笔记
                        if (DataConstants.CALL_NOTE.equals(mimeType)) {
                            // 获取通话相关数据：电话号码、通话日期、位置信息
                            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));
                            }
                            // Print call date输出通话日期
                            ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
                                    .format(mContext.getString(R.string.format_datetime_mdhm),
                                            callDate)));
                            // Print call attachment location输出通话位置信息
                            if (!TextUtils.isEmpty(location)) {
                                ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
                                        location));
                            }
                        } else if (DataConstants.NOTE.equals(mimeType)) {//处理普通笔记内容
                            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();
            }
            // print a line separator between note每个笔记输出完成后添加分隔符
            try {
                ps.write(new byte[] {
                        Character.LINE_SEPARATOR, Character.LETTER_NUMBER
                });
            } catch (IOException e) {
                Log.e(TAG, e.toString());
            }
        }

        /**
         * 将笔记数据导出为文本文件
         */
        public int exportToText() {
            //检查外部存储是否可用（SD卡未挂载状态）
            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;
            }
            //第一部分：导出文件夹及其包含的笔记
            //查询条件：
            //1. 是文件夹类型 且 不在回收站中
            //2. 或者是通话记录特殊文件夹
            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());
                }
                //确保Cursor被关闭
                folderCursor.close();
            }

            // 第二部分：导出根目录下的笔记（不属于任何文件夹的笔记）
            // 查询条件：
            //    1. 是笔记类型（非文件夹）
            //    2. 父ID为0（根目录）
            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 {
                        //输出笔记修改日期（格式化后）
                        ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
                                mContext.getString(R.string.format_datetime_mdhm),
                                noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
                        //导出该笔记的具体内容
                        String noteId = noteCursor.getString(NOTE_COLUMN_ID);
                        exportNoteToText(noteId, ps);
                    } while (noteCursor.moveToNext());
                }
                //确保Cursor被关闭
                noteCursor.close();
            }
            //关闭输出流
            ps.close();

            return STATE_SUCCESS;
        }

        /**
         * 获取用于导出数据到文本文件的PrintStream对象
         */
        private PrintStream getExportToTextPrintStream() {
            //SD卡上生成目标文件
            //使用context和资源文件中定义的路径、文件名格式来创建文件
            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) {
                //处理文件未找到异常（如SD卡不可用等）
                e.printStackTrace();
                return null;
            } catch (NullPointerException e) {
                //处理空指针异常（如上下文为空）
                e.printStackTrace();
                return null;
            }
            //返回创建好的PrintStream对象
            return ps;
        }
    }

    /**
     * 在SD卡上生成文件的工具方法
     */
    private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
        //创建文件路径字符串
        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) {
            //处理IO异常（如创建文件失败）
            e.printStackTrace();
        }
        //如果出现异常，返回NULL
        return null;
    }
}


