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;

    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;

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

        //1
        // 数据列索引：内容
        private static final int DATA_COLUMN_CONTENT = 0;

        // 数据列索引：MIME 类型
        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)
                                )
                        ));
                        // 查询属于此笔记的所有数据
                        String noteId = notesCursor.getString(NOTE_COLUMN_ID);
                        exportNoteToText(noteId, ps);
                    } while (notesCursor.moveToNext());
                }
                notesCursor.close();
            }
        }
//2
        /**
         * Export note identified by id to a print stream
         */
        /**
         * 将指定noteId的Note数据导出到文本文件
         */
        private void exportNoteToText(String noteId, PrintStream ps) {
            // 查询属于该note的数据
            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)) {
                                // 打印Note内容
                                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());
            }
        }

//3
        /**
         * Note will be exported as text which is user readable
         */
        /**

         将笔记数据导出为文本文件

         @return 导出状态码
         */
        public int exportToText() {
// 检查外部存储是否可用
            if (!externalStorageAvailable()) {
                Log.d(TAG, "存储介质未挂载");
                return STATE_SD_CARD_UNMOUONTED;
            }

// 获取导出文本文件的打印流
            PrintStream ps = getExportToTextPrintStream();
            if (ps == null) {
                Log.e(TAG, "获取打印流失败");
                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,
                    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());
                }
                noteCursor.close();
            }
            ps.close();
            return STATE_SUCCESS;
        }
//4
        /**
         * Get a print stream pointed to the file {@generateExportedTextFile}
         */
        /**

         获取输出文本流
         @return 输出文本流
         */
        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;
        }
        /**

         生成存储导入数据的文本文件

         @param context 上下文对象

         @param filePathResId 文件路径的资源ID

         @param fileNameFormatResId 文件名格式的资源ID

         @return 生成的文本文件对象
         */
        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;
        }
    }
}


