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

/**
  * @ProjectName:    Note.java
  * @Package:        net.micode.notes.model
  * @ClassName:      Note
  * @Description:    创建便签
  * @Author:         ZHANGLINHAO
  * @CreateDate:     2023/12/22:10
 */
public class Note {
    private ContentValues mNoteDiffValues;//创建一个记录小米便签值的表
    private NoteData mNoteData;
    private static final String TAG = "Note";//创建标识为“Note”
    /**
     * 创建新的注释标识，用于向数据库添加新注释
     */
    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);//修改是否本地修改：y
        values.put(NoteColumns.PARENT_ID, folderId);//修改文件夹ID
        Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, 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);//抛出异常
        }
        return noteId;
    }

    public Note() {//新建便签
        mNoteDiffValues = new ContentValues();
        mNoteData = new NoteData();
    }

    public void setNoteValue(String key, String value) {//初始化便签值
        mNoteDiffValues.put(key, value);
        mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 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;
    }

    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;//最后一次修改不是本地修改
        }

        /**
         * 从理论上讲，一旦数据发生变化，注释应该在 {@link NoteColumns#LOCAL_MODIFIED} 上更新，和
         * {@link NoteColumns#MODIFIED_DATE}。为了数据安全，虽然更新说明失败，但我们也会更新
         * 便签数据信息
         */
        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) {//设置文本内容ID
            if(id <= 0) {
                throw new IllegalArgumentException("Text data id should larger than 0");//对ID错误进行报错
            }
            mTextDataId = id;
        }

        void setCallDataId(long id) {//返回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) {//将文本上传
            /**
             * 检查安全性
             */
            if (noteId <= 0) {
                throw new IllegalArgumentException("Wrong note id:" + noteId);//错误ID报错
            }

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

            if(mTextDataValues.size() > 0) {//判断文本内容是否为空，不为空就获取其ID
                mTextDataValues.put(DataColumns.NOTE_ID, noteId);
                if (mTextDataId == 0) {
                    mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);//输入项目类型
                    Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
                            mTextDataValues);//插入uri
                    try {
                        setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));//获取文本内容Id
                    } 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));//更新便签ID和URI
                    builder.withValues(mTextDataValues);
                    operationList.add(builder.build());//将便签文本内容的值加入操作列表
                }
                mTextDataValues.clear();
            }

            if(mCallDataValues.size() > 0) {//判断是否有返回文本内容，有则获取其ID
                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) {//判断操作列表是否有操作，有则返回便签URI和ID
                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);//返回便签URI和ID
                } 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;//不符合条件则不上传
        }
    }
}
