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

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

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

        /**
         * Export the folder identified by folder id to text
         */
        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);
        
            // 如果notesCursor不为null，则进行处理
            if (notesCursor != null) {
                // 如果notesCursor中有数据，则继续循环处理每个笔记
                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
                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);
        
            // 如果dataCursor不为null，则进行处理
            if (dataCursor != null) {
                // 如果dataCursor中有数据，则继续循环处理每个数据项
                if (dataCursor.moveToFirst()) {
                    do {
                        // 获取数据的mimeType
                        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));
                            }
                            // 打印通话日期
                            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
                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;
            }
      
            // 获取导出到文本的PrintStream对象
            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);
      
            // 如果folderCursor不为null，则进行处理
            if (folderCursor != null) {
                // 如果folderCursor中有数据，则继续循环处理每个文件夹
                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
                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);
      
            // 如果noteCursor不为null，则进行处理
            if (noteCursor != null) {
                // 如果noteCursor中有数据，则继续循环处理每个笔记
                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
                noteCursor.close();
            }
            // 关闭PrintStream
            ps.close();
      
            return STATE_SUCCESS;
      }

        /**
         * Get a print stream pointed to the file {@generateExportedTextFile}
         */
/**
 * 获取用于导出文本的PrintStream对象
 * @return 如果成功获取PrintStream对象，则返回该对象；如果获取过程中出现错误，则返回null
 */
private PrintStream getExportToTextPrintStream() {
    // 调用generateFileMountedOnSDcard方法生成一个文件对象
    File file = generateFileMountedOnSDcard(mContext, R.string.file_path, R.string.file_name_txt_format);
    // 如果生成的文件对象为空，记录错误并返回null
    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 {
        // 创建文件输出流，并将其封装为PrintStream对象
        FileOutputStream fos = new FileOutputStream(file);
        ps = new PrintStream(fos);
    } catch (FileNotFoundException e) {
        // 捕获FileNotFoundException，记录错误并返回null
        e.printStackTrace();
        return null;
    } catch (NullPointerException e) {
        // 捕获NullPointerException，记录错误并返回null
        e.printStackTrace();
        return null;
    }
    // 返回创建的PrintStream对象，如果在过程中出现其他问题则返回null
    return ps;
}
    }

    /**
     * Generate the text file to store imported data
     */
/**
 * 在SD卡上生成一个文件对象
 * @param context 上下文对象
 * @param filePathResId 文件路径的资源ID
 * @param fileNameFormatResId 文件名格式的资源ID
 * @return 如果成功生成文件对象，则返回该对象；如果生成过程中出现错误，则返回null
 */
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
    // 创建一个StringBuilder对象，用于拼接文件路径和文件名
    StringBuilder sb = new StringBuilder();
    
    // 获取SD卡的根目录，并将其添加到StringBuilder中
    sb.append(Environment.getExternalStorageDirectory());
    
    // 从资源中获取文件路径，并将其添加到StringBuilder中
    sb.append(context.getString(filePathResId));
    
    // 根据文件名格式资源ID和当前时间生成文件名，并将其添加到StringBuilder中
    sb.append(context.getString(fileNameFormatResId, DateFormat.format(context.getString(R.string.format_date_ymd),
                    System.currentTimeMillis())));
    
    // 根据StringBuilder中的路径创建一个文件夹对象
    File filedir = new File(sb.toString());
    
    // 根据StringBuilder中的完整路径创建一个文件对象
    File file = new File(sb.toString());

    try {
        // 如果文件夹不存在，则创建文件夹
        if (!filedir.exists()) {
            filedir.mkdir();
        }
        
        // 如果文件不存在，则创建文件
        if (!file.exists()) {
            file.createNewFile();
        }
        
        // 返回生成的文件对象
        return file;
    } catch (SecurityException e) {
        // 捕获SecurityException异常，打印异常信息
        e.printStackTrace();
    } catch (IOException e) {
        // 捕获IOException异常，打印异常信息
        e.printStackTrace();
    }
    
    // 返回null表示生成文件过程中出现了错误
    return null;
}
}


