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

import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.net.Uri;
import android.os.RemoteException;
import android.util.Log;

import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;

import java.util.ArrayList;

public class Note {// 便签类
    private ContentValues mNoteDiffValues; // 用于保存便签修改值
    private NoteData mNoteData; // 保存便签的数据
    private static final String TAG = "Note"; // 设置TAG为Note

    /**
     * Create a new note id for adding a new note to databases
     */
    public static synchronized long getNewNoteId(Context context, long folderId) { // 为一个新的便签创建id返回数据库
        // Create a new note in the database
        ContentValues values = new ContentValues(); // 用于保存创建日期等字段的值
        long createdTime = System.currentTimeMillis(); // 获取创建时间
        values.put(NoteColumns.CREATED_DATE, createdTime);
        values.put(NoteColumns.MODIFIED_DATE, createdTime);
        values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
        values.put(NoteColumns.LOCAL_MODIFIED, 1);
        values.put(NoteColumns.PARENT_ID, folderId);
        Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values); // 将values插入数据库中，并返回uri

        long noteId = 0;
        try {
            noteId = Long.valueOf(uri.getPathSegments().get(1)); // 解析uri获取新笔记id
        } catch (NumberFormatException e) {
            Log.e(TAG, "Get note id error :" + e.toString()); // 解析失败日志
            noteId = 0;
        }
        if (noteId == -1) {
            throw new IllegalStateException("Wrong note id:" + noteId); // 获取id出错，抛出异常
        }
        return noteId;
    }

    public Note() {
        mNoteDiffValues = new ContentValues(); // 创建新对象
        mNoteData = new NoteData(); // 创建新对象
    }

    public void setNoteValue(String key, String value) { // 设置便签的值
        mNoteDiffValues.put(key, value); // key为属性，values为新值
        mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); // 本地修改标识为1，标识被修改
        mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); // 表示修改时间，用于服务器时间比较
    }

    public void setTextData(String key, String value) {
        mNoteData.setTextData(key, value); // 添加键值对
    } // 设置文本数据

    public void setTextDataId(long id) {
        mNoteData.setTextDataId(id);
    } // 设置文本数据id

    public long getTextDataId() {
        return mNoteData.mTextDataId;
    } // 获取文本数据id

    public void setCallDataId(long id) {
        mNoteData.setCallDataId(id);
    } // 设置通讯数据id

    public void setCallData(String key, String value) {
        mNoteData.setCallData(key, value);
    } // 设置通讯数据，添加键值对

    public boolean isLocalModified() {
        return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
    } // 检查是否被修改

    public boolean syncNote(Context context, long noteId) { // 用于同步到数据库中
        if (noteId <= 0) {
            throw new IllegalArgumentException("Wrong note id:" + noteId); // 抛出异常
        }

        if (!isLocalModified()) { // 判断是否修改过
            return true; // 没修改则不需要同步
        }

        /**
         * In theory, once data changed, the note should be updated on
         * {@link NoteColumns#LOCAL_MODIFIED} and
         * {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails,
         * we also update the
         * note data info
         */
        if (context.getContentResolver().update( // 打包并同步
                ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
                null) == 0) {
            Log.e(TAG, "Update note error, should not happen");
            // Do not return, fall through
        }
        mNoteDiffValues.clear();

        if (mNoteData.isLocalModified()
                && (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
            return false; // 表示同步失败
        }

        return true;
    }

    private class NoteData { // 私有内部类，用于便签数据管理
        private long mTextDataId;

        private ContentValues mTextDataValues;

        private long mCallDataId;

        private ContentValues mCallDataValues;

        private static final String TAG = "NoteData";

        public NoteData() { // 构造函数
            mTextDataValues = new ContentValues(); // 保存便签文本
            mCallDataValues = new ContentValues(); // 保存便签通讯记录
            mTextDataId = 0;
            mCallDataId = 0;
        }

        boolean isLocalModified() {
            return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
        } // 检查便签是否再本地修改

        void setTextDataId(long id) {
            if (id <= 0) {
                throw new IllegalArgumentException("Text data id should larger than 0");
            }
            mTextDataId = id;
        } // 设置便签文本标识符

        void setCallDataId(long id) {
            if (id <= 0) {
                throw new IllegalArgumentException("Call data id should larger than 0");
            }
            mCallDataId = id;
        } // 设置便签通讯标识符

        void setCallData(String key, String value) {
            mCallDataValues.put(key, value);
            mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); // 更新修改状态
            mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); // 更新修改日期
        } // 设置文本数据

        void setTextData(String key, String value) { // 设置通讯数据
            mTextDataValues.put(key, value);
            mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
            mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
        }

        Uri pushIntoContentResolver(Context context, long noteId) { // 将文本数据与通讯数据添加到context
            /**
             * Check for safety
             */
            if (noteId <= 0) {
                throw new IllegalArgumentException("Wrong note id:" + noteId); // 抛出异常
            }

            ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
            ContentProviderOperation.Builder builder = null;

            if (mTextDataValues.size() > 0) { // 检查文本数据
                mTextDataValues.put(DataColumns.NOTE_ID, noteId); // 将便签id与数据值相关联
                if (mTextDataId == 0) {
                    mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE); // 并将键值对添加到mTextDataValues中
                    Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
                            mTextDataValues); // 插入新的数据行，保存返回的uri
                    try {
                        setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
                    } catch (NumberFormatException e) {
                        Log.e(TAG, "Insert new text data fail with noteId" + noteId); // 异常日志
                        mTextDataValues.clear();
                        return null;
                    }
                } else { // 表示需要更新现有数据行
                    builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
                            Notes.CONTENT_DATA_URI, mTextDataId));
                    builder.withValues(mTextDataValues);
                    operationList.add(builder.build());
                }
                mTextDataValues.clear(); // 清空mTextDataValues
            }
            if (mCallDataValues.size() > 0) { // 检查通讯数据，代码内容功能同上
                mCallDataValues.put(DataColumns.NOTE_ID, noteId);
                if (mCallDataId == 0) {
                    mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
                    Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
                            mCallDataValues);
                    try {
                        setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
                    } catch (NumberFormatException e) {
                        Log.e(TAG, "Insert new call data fail with noteId" + noteId);
                        mCallDataValues.clear();
                        return null;
                    }
                } else {
                    builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
                            Notes.CONTENT_DATA_URI, mCallDataId));
                    builder.withValues(mCallDataValues);
                    operationList.add(builder.build());
                }
                mCallDataValues.clear();
            }

            if (operationList.size() > 0) { // 检查operationList，对载入的操作进行批量提交
                try {
                    ContentProviderResult[] results = context.getContentResolver().applyBatch(
                            Notes.AUTHORITY, operationList);
                    return (results == null || results.length == 0 || results[0] == null) ? null
                            : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
                } catch (RemoteException e) {
                    Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
                    return null;
                } catch (OperationApplicationException e) {
                    Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
                    return null;
                }
            }
            return null;
        }
    }
}
