/*
 * 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";// 定义了一个私有静态常量字符串TAG，用于在日志中标记该类
    // Singleton stuff
    private static BackupUtils sInstance;// 声明了一个私有静态BackupUtils对象sInstance，用于实现单例模式

    public static synchronized BackupUtils getInstance(Context context) {//获取BackupUtils类的实例的静态方法
        if (sInstance == null) {
            sInstance = new BackupUtils(context);//在第一次调用时，会创建一个新的BackupUtils对象，并将其赋值给静态变量sInstance
        }
        return sInstance;
    }

    /**
     * Following states are signs to represents backup or restore
     * status
     */
    // Currently, the sdcard is not mounted
    public static final int STATE_SD_CARD_UNMOUONTED           = 0;//表示sd卡未挂载的状态。
    // 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;//表示数据格式错误，可能被其他程序修改的状态
    // Some run-time exception which causes restore or backup fails
    public static final int STATE_SYSTEM_ERROR                 = 3;//表示备份或还原过程中发生运行时异常的状态
    // Backup or restore success
    public static final int STATE_SUCCESS                      = 4;//表示备份或还原成功的状态

    private TextExport mTextExport;

    private BackupUtils(Context context) {//用于初始化BackupUtils对象。在构造函数内部，创建了一个TextExport对象mTextExport。
        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;

        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];
        }

        /**
         * Export the folder identified by folder id to text
         */
        private void exportFolderToText(String folderId, PrintStream ps) {//将该文件夹中的笔记导出为文本
            // Query notes belong to this folder
            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 {// 打印笔记的最后修改日期
                        // Print note's last modified date
                        ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
                                mContext.getString(R.string.format_datetime_mdhm),
                                notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
                        // Query data belong to this note
                        // 查询属于该笔记的数据
                        String noteId = notesCursor.getString(NOTE_COLUMN_ID);
                        exportNoteToText(noteId, ps);
                    } while (notesCursor.moveToNext());
                }
                notesCursor.close();
            }
        }

        /**
         * Export note identified by id to a print stream
         */
        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()) {
                    // 遍历游标以检索每个数据行的MIME类型
                    do {
                        String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
                        if (DataConstants.CALL_NOTE.equals(mimeType)) {// 将电话号码、通话日期和位置信息打印到输出流中 
                            // Print phone number
                            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());
            }
        }

        /**
         * Note will be exported as text which is user readable
         */
        public int exportToText() { //总函数，调用上面的exportFolder和exportNote
            if (!externalStorageAvailable()) {// 检查外部存储是否可用（即 SD 卡是否已挂载）
                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;
            }
            // 首先导出文件夹及其下的笔记
            // First export folder and its notes
            Cursor folderCursor = mContext.getContentResolver().query(
                    Notes.CONTENT_NOTE_URI,// 查询内容 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 {
                        // Print folder's name
                        // 打印文件夹的名称
                        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();// 关闭查询结果集游标
            }

            // Export notes in root's folder
            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))));
                        // Query data belong to this note
                        String noteId = noteCursor.getString(NOTE_COLUMN_ID);
                        exportNoteToText(noteId, ps);
                    } while (noteCursor.moveToNext());
                }
                noteCursor.close();
            }
            ps.close();

            return STATE_SUCCESS;
        }

        /**
         * Get a print stream pointed to the file {@generateExportedTextFile}
         */
        private PrintStream getExportToTextPrintStream() {//私有方法，返回一个PrintStream对象，用于导出文本
            File file = generateFileMountedOnSDcard(mContext, R.string.file_path,//调用generateFileMountedOnSDcard方法生成一个文件对象，作为导出文件的路径。
                    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;
        }
    }

    /**
     * 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) {
            e.printStackTrace();//会打印错误信息并返回空
        }

        return null;
    }
}


