/*
 * 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;

    // 获取 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;
    // 备份文件不存在
    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;// 文本导出工具

    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; // 笔记 ID 列索引

        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;// MIME 类型列索引

        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 = "";
        }

        // 根据 id 获取对应的文本格式
        private String getFormat(int id) {
            return TEXT_FORMAT[id];
        }

        /**
         * Export the folder identified by folder id to text
         */
        /**
         * 将指定文件夹（通过 folderId 标识）导出为文本
         */
        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))));
                        // 查询该笔记的数据
                        String noteId = notesCursor.getString(NOTE_COLUMN_ID);
                        exportNoteToText(noteId, ps);// 导出笔记内容
                    } while (notesCursor.moveToNext());
                }
                notesCursor.close();// 关闭游标
            }
        }

        /**
         * Export note identified by id to a print stream
         */
        /**
         * 将通过 noteId 标识的笔记导出到打印流中
         */
        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);// 获取 MIME 类型
                        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));
                            }
                            // 打印通话日期
                            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)) {// 如果是普通笔记
                            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();// 关闭游标
            }

            // 在笔记之间打印一个分隔行
            try {
                ps.write(new byte[] {
                        Character.LINE_SEPARATOR, Character.LETTER_NUMBER
                });
            } catch (IOException e) {
                Log.e(TAG, e.toString());
            }
        }

        /**
         * Note will be exported as text which is user readable
         */
        /**
         * 将笔记导出为用户可读的文本
         */
        public int exportToText() {// 检查外部存储是否可用
            if (!externalStorageAvailable()) {
                Log.d(TAG, "Media was not mounted");
                return STATE_SD_CARD_UNMOUONTED;// 返回 SD 卡未挂载状态
            }

            PrintStream ps = getExportToTextPrintStream();// 获取打印流
            if (ps == null) {
                Log.e(TAG, "get print stream error");
                return STATE_SYSTEM_ERROR;// 返回系统错误状态
            }

            // 首先导出文件夹及其笔记
            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();// 关闭游标
            }

            // 导出根文件夹中的笔记
            Cursor noteCursor = mContext.getContentResolver().query(
                    Notes.CONTENT_NOTE_URI,// 查询笔记内容的 URI
                    NOTE_PROJECTION,// 查询的列
                    NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID
                            + "=0", null, null);// 查询条件：类型为笔记且父级 ID 为 0（根文件夹）

            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);// 获取笔记 ID
                        exportNoteToText(noteId, ps); // 导出该笔记的内容到打印流
                    } while (noteCursor.moveToNext());// 遍历游标中的所有笔记
                }
                noteCursor.close();// 关闭游标
            }
            ps.close();// 关闭打印流

            return STATE_SUCCESS;// 返回成功状态
        }

        /**
         * Get a print stream pointed to the file {@generateExportedTextFile}
         */
        /**
         * 获取指向文件 {@generateExportedTextFile} 的打印流
         */
        private PrintStream getExportToTextPrintStream() {
            // 生成一个指向 SD 卡的文件
            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;// 返回 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;// 返回 null
            } catch (NullPointerException e) { // 捕获空指针异常
                e.printStackTrace(); // 打印异常堆栈
                return null;// 返回 null
            }
            return ps;// 返回打印流
        }
    }

    /**
     * Generate the text file to store imported data
     */
    /**
     * 生成用于存储导入数据的文本文件
     */
    private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
        StringBuilder sb = new StringBuilder();// 创建字符串构建器
        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();// 打印异常堆栈
        }

        return null;// 返回 null
    }
}


