/*
 * 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.gtask.data;
/**     
  * 
  * @ProjectName:    Notes-master
  * @Package:        gtask
  * @ClassName:      Task
  * @Description:    同步任务，将创建、更新和同步动作包装成JSON对象，用本地和远程的JSON对节点内容进行设置，获取同步信息
  * @Author:         wsk
  * @CreateDate:     23.12.23
  * @Version:        1.0
 */
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;

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 net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

//同步操作
public class Task extends Node {
    private static final String TAG = Task.class.getSimpleName();

    private boolean mCompleted;//是否完成

    private String mNotes;

    private JSONObject mMetaInfo;//将在实例中存储数据的类型

    private Task mPriorSibling;//对应的优先兄弟Task的指针（待完善）

    private TaskList mParent;//所在的任务列表的指针
     /**
      * @method  Task
      * @description 初始化变量 ，进行赋值操作
      * @date:
      * @author: wsk
      * @param
      * @return null
      */
    public Task() {
        super();
        mCompleted = false;
        mNotes = null;
        mPriorSibling = null;//TaskList中当前Task前面的Task的指针
        mParent = null;//当前Task所在的TaskList
        mMetaInfo = null;
    }
     /**
      * @method  getCreateAction
      * @description 创建动作，根据参数js创建动作的形式，id等
      * @date:
      * @author: wsk
      * @param
      * @return JSON对象js
      */
    public JSONObject getCreateAction(int actionId) {
        JSONObject js = new JSONObject();

        try {
            // action_type
            js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
                    GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);

            // action_id
            js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);

            // index
            js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this));

            // entity_delta
            JSONObject entity = new JSONObject();
            entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
            entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
            entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
                    GTaskStringUtils.GTASK_JSON_TYPE_TASK);
            if (getNotes() != null) {
                entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
            }
            js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);

            // parent_id
            js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid());

            // dest_parent_type
            js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE,
                    GTaskStringUtils.GTASK_JSON_TYPE_GROUP);

            // list_id
            js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid());

            // prior_sibling_id
            if (mPriorSibling != null) {
                js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid());
            }

        } catch (JSONException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
            throw new ActionFailureException("fail to generate task-create jsonobject");
        }

        return js;
    }
     /**
      * @method  getUpdateAction
      * @description 更新动作
      * @date:
      * @author: wsk
      * @param
      * @return js
      */
    public JSONObject getUpdateAction(int actionId) {
        JSONObject js = new JSONObject();

        try {
            // action_type
            js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
                    GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);

            // action_id
            js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);

            // id
            js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());

            // entity_delta
            JSONObject entity = new JSONObject();
            entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
            if (getNotes() != null) {
                entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
            }
            entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
            js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);

        } catch (JSONException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
            throw new ActionFailureException("fail to generate task-update jsonobject");
        }

        return js;
    }
     /**
      * @method  setContentByRemoteJSON
      * @description 根据传入的动作对象js，设置任务内容
      * @date:
      * @author: wsk
      * @param
      * @return js
      */
    public void setContentByRemoteJSON(JSONObject js) {
        if (js != null) {
            try {
                // id
                if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
                    setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
                }

                // last_modified
                if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
                    setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
                }

                // name
                if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
                    setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
                }

                // notes
                if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) {
                    setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES));
                }

                // deleted
                if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) {
                    setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED));
                }

                // completed
                if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) {
                    setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED));
                }
            } catch (JSONException e) {
                Log.e(TAG, e.toString());
                e.printStackTrace();
                throw new ActionFailureException("fail to get task content from jsonobject");
            }
        }
    }

    public void setContentByLocalJSON(JSONObject js) {
        if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
                || !js.has(GTaskStringUtils.META_HEAD_DATA)) {
            Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
        }

        try {
            JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
            JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);

            if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
                Log.e(TAG, "invalid type");
                return;
            }

            for (int i = 0; i < dataArray.length(); i++) {
                JSONObject data = dataArray.getJSONObject(i);
                if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
                    setName(data.getString(DataColumns.CONTENT));
                    break;
                }
            }

        } catch (JSONException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }
    }//放到本地local库

    public JSONObject getLocalJSONFromContent() {
        String name = getName();
        try {
            if (mMetaInfo == null) {
                // new task created from web
                if (name == null) {
                    Log.w(TAG, "the note seems to be an empty one");
                    return null;
                }

                JSONObject js = new JSONObject();
                JSONObject note = new JSONObject();
                JSONArray dataArray = new JSONArray();
                JSONObject data = new JSONObject();
                data.put(DataColumns.CONTENT, name);
                dataArray.put(data);
                js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
                note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
                js.put(GTaskStringUtils.META_HEAD_NOTE, note);
                return js;
            } else {
                // synced task
                JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
                JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);

                for (int i = 0; i < dataArray.length(); i++) {
                    JSONObject data = dataArray.getJSONObject(i);
                    if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
                        data.put(DataColumns.CONTENT, getName());
                        break;
                    }
                }

                note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
                return mMetaInfo;
            }
        } catch (JSONException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
            return null;
        }
    }//这段代码是一个Java方法，用于根据任务对象的内容生成对应的JSONObject对象。方法会根据任务的来源（新建的任务或已同步的任务）以及任务的属性值来生成相应的JSONObject对象。

   // 在方法内部，首先获取任务的名称，并进行空值检查。如果名称为空，则输出一条警告日志并返回null。

   // 然后根据任务的来源进行处理。如果任务是新建的（mMetaInfo为null），则创建一个新的JSONObject对象js，并依次创建note和dataArray两个JSONObject对象，并设置其对应的键值对。其中，note表示任务的备注信息，dataArray表示任务的详细信息。接着，创建一个data对象，并将任务的名称name作为DataColumns.CONTENT的值，并将data对象添加到dataArray数组中。最后将dataArray和note对象分别设置到js对象中，并返回js对象。

   // 如果任务是已同步的（mMetaInfo不为null），则从mMetaInfo中获取note和dataArray两个JSONObject对象。接着，遍历dataArray数组中的每个JSONObject对象，查找MIME_TYPE为DataConstants.NOTE的对象，并将其CONTENT属性设置为任务的名称。最后，将note对象的TYPE属性设置为Notes.TYPE_NOTE，并返回mMetaInfo对象。

   // 在解析过程中，如果发生了JSONException异常，则会捕获该异常并输出错误日志，并返回null。

   // 总之，该方法的作用是根据任务对象的内容生成对应的JSONObject对象。


    public void setMetaInfo(MetaData metaData) {
        if (metaData != null && metaData.getNotes() != null) {
            try {
                mMetaInfo = new JSONObject(metaData.getNotes());
            } catch (JSONException e) {
                Log.w(TAG, e.toString());
                mMetaInfo = null;
            }
        }
    }//用于设置任务对象的元数据信息。

    public int getSyncAction(Cursor c) {
        try {
            JSONObject noteInfo = null;
            if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {
                noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
            }

            if (noteInfo == null) {
                Log.w(TAG, "it seems that note meta has been deleted");
                return SYNC_ACTION_UPDATE_REMOTE;
            }

            if (!noteInfo.has(NoteColumns.ID)) {
                Log.w(TAG, "remote note id seems to be deleted");
                return SYNC_ACTION_UPDATE_LOCAL;
            }

            // validate the note id now
            if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
                Log.w(TAG, "note id doesn't match");
                return SYNC_ACTION_UPDATE_LOCAL;
            }

            if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
                // there is no local update
                if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
                    // no update both side
                    return SYNC_ACTION_NONE;
                } else {
                    // apply remote to local
                    return SYNC_ACTION_UPDATE_LOCAL;
                }
            } else {
                // validate gtask id
                if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
                    Log.e(TAG, "gtask id doesn't match");
                    return SYNC_ACTION_ERROR;
                }
                if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
                    // local modification only
                    return SYNC_ACTION_UPDATE_REMOTE;
                } else {
                    return SYNC_ACTION_UPDATE_CONFLICT;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }

        return SYNC_ACTION_ERROR;
    }//根据传入的Cursor对象c判断当前任务对象需要执行哪种同步行为（更新本地、更新远程、不进行同步等）。是否要更新，更新哪里

    public boolean isWorthSaving() {
        return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
                || (getNotes() != null && getNotes().trim().length() > 0);
    }//是否值得保存

    public void setCompleted(boolean completed) {
        this.mCompleted = completed;
    }
    //设置任务完成状态
    public void setNotes(String notes) {
        this.mNotes = notes;
    }//设置属性
     /**
      * @method  
      * @description 设置属性
      * @date:  
      * @author: wsk
      * @param 
      * @return 
      */
    public void setPriorSibling(Task priorSibling) {
        this.mPriorSibling = priorSibling;
    }
     /**
      * @method
      * @description 设置当前任务节点的前一个兄弟节点
      * @date:
      * @author: wsk
      * @param
      * @return
      */
    public void setParent(TaskList parent) {
        this.mParent = parent;
    }
     /**
      * @method  getCompleted
      * @description 获取一个名为mCompleted的布尔类型成员变量的数值。根据你提供的代码，这个方法返回mCompleted的当前数值。
      * @date:
      * @author: wsk
      * @param
      * @return mCompleted
      */
    public boolean getCompleted() {
        return this.mCompleted;
    }
     /**
      * @method  getNotes
      * @description 获取一个名为mNotes的字符串类型成员变量的数值
      * @date:
      * @author: wsk
      * @param
      * @return mNotes字符串或空
      */
    public String getNotes() {
        return this.mNotes;
    }
     /**
      * @method getPriorSibling
      * @description 获取一个名为mPriorSibling的Task对象成员变量的数值
      * @date:
      * @author: wsk
      * @param
      * @return this.mPriorSibling
      */
    public Task getPriorSibling() {
        return this.mPriorSibling;
    }
     /**
      * @method  getParent
      * @description 获取一个名为mParent的TaskList对象成员变量的数值
      * @date:
      * @author: wsk
      * @param
      * @return this.mParent
      */
    public TaskList getParent() {
        return this.mParent;
    }

}
