/*
 * 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的单例实例
     * @param context 上下文对象
     * @return BackupUtils实例
     */
    // 定义一个公共的静态同步方法，用于获取BackupUtils的单例实例
    public static synchronized BackupUtils getInstance(Context context) {
        // 检查当前单例实例是否为空
        if (sInstance == null) {
            // 如果为空，则创建一个新的BackupUtils实例，传入上下文参数
            sInstance = new BackupUtils(context);
        }
        // 返回BackupUtils的单例实例
        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;
    // 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;

    // 定义一个私有的构造方法，用于创建BackupUtils类的实例
    private BackupUtils(Context context) {
        // 创建一个TextExport对象，并将传入的上下文对象context作为参数传递给TextExport的构造方法
        mTextExport = new TextExport(context);
    }

    // 定义一个私有静态方法，用于检查外部存储是否可用
    private static boolean externalStorageAvailable() {
        // 调用Environment类的getExternalStorageState()方法获取外部存储的状态
        // 将获取到的状态与Environment.MEDIA_MOUNTED常量进行比较
        // 如果状态为MEDIA_MOUNTED，则表示外部存储已挂载且可用，返回true
        // 否则返回false
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    // 定义一个名为exportToText的方法，该方法返回一个整型值
    public int exportToText() {
        // 调用mTextExport对象的exportToText方法，并将返回值作为当前方法的返回值
        return mTextExport.exportToText();
    }

    // 定义一个公共的方法，用于获取导出的文本文件名
    public String getExportedTextFileName() {
        // 返回mTextExport对象的mFileName属性，即导出的文本文件名
        return mTextExport.mFileName;
    }

    // 定义一个公共方法，用于获取导出的文本文件目录
    public String getExportedTextFileDir() {
        // 返回mTextExport对象的mFileDirectory属性值，即导出的文本文件目录
        return mTextExport.mFileDirectory;
    }

    // 定义一个静态内部类 TextExport，用于将笔记导出为文本
    private static class TextExport {
        // 定义查询笔记时所需的列
        private static final String[] NOTE_PROJECTION = {
                NoteColumns.ID, // 笔记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, // 数据MIME类型
                DataColumns.DATA1, // 数据1
                DataColumns.DATA2, // 数据2
                DataColumns.DATA3, // 数据3
                DataColumns.DATA4, // 数据4
        };

        // 定义数据列的索引常量
        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 = "";
        }

        // 根据格式ID获取对应的格式字符串
        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()) {
                    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() {
            // 检查外部存储是否可用
            if (!externalStorageAvailable()) {
                Log.d(TAG, "Media was not mounted"); // 日志记录：媒体未挂载
                return STATE_SD_CARD_UNMOUONTED; // 返回状态：SD卡未挂载
            }

            // 获取用于导出文本的PrintStream对象
            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,
                    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}
         */
        // 定义一个私有方法，用于获取用于导出文本的PrintStream对象
        private PrintStream getExportToTextPrintStream() {
            // 调用generateFileMountedOnSDcard方法生成一个文件对象，文件保存在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"为错误信息
                Log.e(TAG, "create file to exported failed");
                // 返回null表示获取PrintStream对象失败
                return null;
            }
            // 获取文件名并赋值给mFileName变量
            mFileName = file.getName();
            // 获取文件路径并赋值给mFileDirectory变量
            mFileDirectory = mContext.getString(R.string.file_path);
            // 初始化PrintStream对象为null
            PrintStream ps = null;
            try {
                // 创建FileOutputStream对象，用于写入文件
                FileOutputStream fos = new FileOutputStream(file);
                // 创建PrintStream对象，将FileOutputStream对象作为参数传入
                ps = new PrintStream(fos);
            } catch (FileNotFoundException e) {
                // 捕获文件未找到异常，并打印堆栈跟踪信息
                e.printStackTrace();
                // 返回null表示获取PrintStream对象失败
                return null;
            } catch (NullPointerException e) {
                // 捕获空指针异常，并打印堆栈跟踪信息
                e.printStackTrace();
                // 返回null表示获取PrintStream对象失败
                return null;
            }
            // 返回创建的PrintStream对象
            return ps;
        }
    }

    /**
     * Generate the text file to store imported data
     */
    // 定义一个私有静态方法，用于在SD卡上生成文件
    private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
        // 创建一个StringBuilder对象，用于构建文件路径
        StringBuilder sb = new StringBuilder();
        // 将SD卡根目录追加到StringBuilder中
        sb.append(Environment.getExternalStorageDirectory());
        // 将资源ID对应的文件路径字符串追加到StringBuilder中
        sb.append(context.getString(filePathResId));
        // 根据构建的路径字符串创建一个File对象，表示文件目录
        File filedir = new File(sb.toString());
        // 将资源ID对应的文件名格式字符串和当前日期格式化后追加到StringBuilder中
        sb.append(context.getString(
                fileNameFormatResId,
                DateFormat.format(context.getString(R.string.format_date_ymd),
                        System.currentTimeMillis())));
        // 根据构建的完整路径字符串创建一个File对象，表示文件
        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;
    }
}


