/*
 * 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.appwidget.AppWidgetManager;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
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.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources;


public class WorkingNote {
    // Note for the working note
    private Note mNote;
    // Note Id
    private long mNoteId;
    // Note content
    private String mContent;
    // Note mode
    private int mMode;

    private long mAlertDate;

    private long mModifiedDate;

    private int mBgColorId;

    private int mWidgetId;

    private int mWidgetType;

    private long mFolderId;

    private boolean mIsLocked;

    private String mPasswordHash;

    private Context mContext;

    private static final String TAG = "WorkingNote";

    private boolean mIsDeleted;

    private NoteSettingChangedListener mNoteSettingStatusListener;

    public static final String[] DATA_PROJECTION = new String[] {
            DataColumns.ID,
            DataColumns.CONTENT,
            DataColumns.MIME_TYPE,
            DataColumns.DATA1,
            DataColumns.DATA2,
            DataColumns.DATA3,
            DataColumns.DATA4,
    };

    public static final String[] NOTE_PROJECTION = new String[] {
            NoteColumns.PARENT_ID,
            NoteColumns.ALERTED_DATE,
            NoteColumns.BG_COLOR_ID,
            NoteColumns.WIDGET_ID,
            NoteColumns.WIDGET_TYPE,
            NoteColumns.MODIFIED_DATE,
            NoteColumns.IS_ENCRYPTED,
            NoteColumns.PASSWORD_HASH
    };

    private static final int DATA_ID_COLUMN = 0;

    private static final int DATA_CONTENT_COLUMN = 1;

    private static final int DATA_MIME_TYPE_COLUMN = 2;

    private static final int DATA_MODE_COLUMN = 3;

    private static final int NOTE_PARENT_ID_COLUMN = 0;

    private static final int NOTE_ALERTED_DATE_COLUMN = 1;

    private static final int NOTE_BG_COLOR_ID_COLUMN = 2;

    private static final int NOTE_WIDGET_ID_COLUMN = 3;

    private static final int NOTE_WIDGET_TYPE_COLUMN = 4;

    private static final int NOTE_MODIFIED_DATE_COLUMN = 5;

    private static final int NOTE_IS_ENCRYPTED_COLUMN = 6;

    private static final int NOTE_PASSWORD_HASH_COLUMN = 7;

    // New note construct
    private WorkingNote(Context context, long folderId) {
        mContext = context;
        mAlertDate = 0;
        mModifiedDate = System.currentTimeMillis();
        mFolderId = folderId;
        mNote = new Note();
        mNoteId = 0;
        mIsDeleted = false;
        mMode = 0;
        mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
        mIsLocked = false;
        mPasswordHash = "";
    }

    // Existing note construct
    private WorkingNote(Context context, long noteId, long folderId) {
        mContext = context;
        mNoteId = noteId;
        mFolderId = folderId;
        mIsDeleted = false;
        mNote = new Note();
        loadNote();
    }

    private void loadNote() {
        Cursor cursor = mContext.getContentResolver().query(
                ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
                null, null);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
                mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
                mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
                mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN);
                mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN);
                mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
                mIsLocked = cursor.getInt(NOTE_IS_ENCRYPTED_COLUMN) == 1;
                mPasswordHash = cursor.getString(NOTE_PASSWORD_HASH_COLUMN);
                
                // 添加日志记录，确保密码哈希正确加载
                String hashPreview = "null";
                if (mPasswordHash != null) {
                    if (mPasswordHash.length() > 10) {
                        hashPreview = mPasswordHash.substring(0, 10) + "...";
                    } else if (mPasswordHash.length() > 0) {
                        hashPreview = mPasswordHash + "...";
                    } else {
                        hashPreview = "空字符串";
                    }
                }
                Log.d("WorkingNote", "笔记 #" + mNoteId + " 加载: 锁定状态=" + mIsLocked + 
                        ", 密码哈希=" + hashPreview);
            }
            cursor.close();
        } else {
            Log.e(TAG, "No note with id:" + mNoteId);
            throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
        }
        loadNoteData();
    }

    private void loadNoteData() {
        Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
                DataColumns.NOTE_ID + "=?", new String[] {
                    String.valueOf(mNoteId)
                }, null);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {
                    String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
                    if (DataConstants.NOTE.equals(type)) {
                        mContent = cursor.getString(DATA_CONTENT_COLUMN);
                        mMode = cursor.getInt(DATA_MODE_COLUMN);
                        mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
                    } else if (DataConstants.CALL_NOTE.equals(type)) {
                        mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
                    } else {
                        Log.d(TAG, "Wrong note type with type:" + type);
                    }
                } while (cursor.moveToNext());
            }
            cursor.close();
        } else {
            Log.e(TAG, "No data with id:" + mNoteId);
            throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
        }
    }

    public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
            int widgetType, int defaultBgColorId) {
        WorkingNote note = new WorkingNote(context, folderId);
        note.setBgColorId(defaultBgColorId);
        note.setWidgetId(widgetId);
        note.setWidgetType(widgetType);
        return note;
    }

    public static WorkingNote load(Context context, long id) {
        return new WorkingNote(context, id, 0);
    }

    public synchronized boolean saveNote() {
        if (isWorthSaving()) {
            // 记录保存前的锁定状态
            Log.d("WorkingNote", "WorkingNote.saveNote: 保存笔记 - ID=" + mNoteId + 
                  ", 内容长度=" + (mContent != null ? mContent.length() : 0) + 
                  ", 锁定状态=" + mIsLocked);
                  
            try {
                if (!existInDatabase()) {
                    ContentValues values = new ContentValues();
                    values.put(NoteColumns.SNIPPET, mContent);
                    values.put(NoteColumns.MODIFIED_DATE, mModifiedDate);
                    values.put(NoteColumns.WIDGET_TYPE, mWidgetType);
                    values.put(NoteColumns.WIDGET_ID, mWidgetId);
                    values.put(NoteColumns.BG_COLOR_ID, mBgColorId);
                    values.put(NoteColumns.PARENT_ID, mFolderId);
                    values.put(NoteColumns.IS_ENCRYPTED, mIsLocked ? 1 : 0);
                    values.put(NoteColumns.PASSWORD_HASH, mPasswordHash);
                    Uri uri = mContext.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
                    try {
                        mNoteId = Long.valueOf(uri.getPathSegments().get(1));
                        Log.d("WorkingNote", "WorkingNote.saveNote: 新建笔记成功 - ID=" + mNoteId);
                    } catch (NumberFormatException e) {
                        Log.e(TAG, "Get note id error :" + e.toString());
                        mNoteId = 0;
                    }
                } else {
                    ContentValues values = new ContentValues();
                    values.put(NoteColumns.SNIPPET, mContent);
                    values.put(NoteColumns.MODIFIED_DATE, mModifiedDate);
                    values.put(NoteColumns.BG_COLOR_ID, mBgColorId);
                    values.put(NoteColumns.PARENT_ID, mFolderId);
                    values.put(NoteColumns.IS_ENCRYPTED, mIsLocked ? 1 : 0);
                    values.put(NoteColumns.PASSWORD_HASH, mPasswordHash);
                    
                    int result = mContext.getContentResolver().update(ContentUris.withAppendedId(
                            Notes.CONTENT_NOTE_URI, mNoteId), values, null, null);
                            
                    Log.d("WorkingNote", "WorkingNote.saveNote: 更新笔记结果 - ID=" + mNoteId + 
                          ", 更新行数=" + result);
                }
                
                // 记录保存后的锁定状态
                Log.d("WorkingNote", "WorkingNote.saveNote: 保存成功 - ID=" + mNoteId + 
                      ", 锁定状态=" + mIsLocked + 
                      ", 内容长度=" + (mContent != null ? mContent.length() : 0));
                      
                /**
                 * Update widget content if there exist any widget of this note
                 */
                if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
                        && mWidgetType != Notes.TYPE_WIDGET_INVALIDE
                        && mNoteSettingStatusListener != null) {
                    mNoteSettingStatusListener.onWidgetChanged();
                }
                return true;
            } catch (Exception e) {
                Log.e("WorkingNote", "WorkingNote.saveNote: 保存笔记异常 - " + e.getMessage(), e);
                // 如果是因为数据库错误导致的异常，可以尝试重新保存
                try {
                    Thread.sleep(100); // 短暂延迟
                    
                    // 如果是新笔记，重新尝试插入
                    if (!existInDatabase()) {
                        ContentValues values = new ContentValues();
                        values.put(NoteColumns.SNIPPET, mContent);
                        values.put(NoteColumns.MODIFIED_DATE, mModifiedDate);
                        values.put(NoteColumns.WIDGET_TYPE, mWidgetType);
                        values.put(NoteColumns.WIDGET_ID, mWidgetId);
                        values.put(NoteColumns.BG_COLOR_ID, mBgColorId);
                        values.put(NoteColumns.PARENT_ID, mFolderId);
                        values.put(NoteColumns.IS_ENCRYPTED, mIsLocked ? 1 : 0);
                        values.put(NoteColumns.PASSWORD_HASH, mPasswordHash);
                        Uri uri = mContext.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
                        mNoteId = Long.valueOf(uri.getPathSegments().get(1));
                        Log.d("WorkingNote", "WorkingNote.saveNote: 重试保存成功 - ID=" + mNoteId);
                        return true;
                    } else {
                        // 如果是已存在的笔记，重新尝试更新
                        ContentValues values = new ContentValues();
                        values.put(NoteColumns.SNIPPET, mContent);
                        values.put(NoteColumns.MODIFIED_DATE, mModifiedDate);
                        values.put(NoteColumns.BG_COLOR_ID, mBgColorId);
                        values.put(NoteColumns.PARENT_ID, mFolderId);
                        values.put(NoteColumns.IS_ENCRYPTED, mIsLocked ? 1 : 0);
                        values.put(NoteColumns.PASSWORD_HASH, mPasswordHash);
                        
                        int result = mContext.getContentResolver().update(ContentUris.withAppendedId(
                                Notes.CONTENT_NOTE_URI, mNoteId), values, null, null);
                        Log.d("WorkingNote", "WorkingNote.saveNote: 重试更新结果 - ID=" + mNoteId + 
                              ", 更新行数=" + result);
                        return result > 0;
                    }
                } catch (Exception e2) {
                    Log.e("WorkingNote", "WorkingNote.saveNote: 重试保存失败 - " + e2.getMessage(), e2);
                    return false;
                }
            }
        } else {
            Log.d("WorkingNote", "WorkingNote.saveNote: 笔记不值得保存 - ID=" + mNoteId + 
                  ", 已删除=" + mIsDeleted + 
                  ", 存在于数据库=" + existInDatabase() + 
                  ", 内容为空=" + TextUtils.isEmpty(mContent) + 
                  ", 本地修改=" + (existInDatabase() ? mNote.isLocalModified() : "不适用"));
            return false;
        }
    }

    public boolean existInDatabase() {
        return mNoteId > 0;
    }

    private boolean isWorthSaving() {
        // 记录当前状态
        Log.d(TAG, "isWorthSaving: 检查笔记是否值得保存 - ID=" + mNoteId + 
              ", 已删除=" + mIsDeleted + 
              ", 内容长度=" + (mContent != null ? mContent.length() : 0) + 
              ", 存在于数据库=" + existInDatabase());
        
        // 如果笔记已被标记为删除，则不保存
        if (mIsDeleted) {
            Log.d(TAG, "isWorthSaving: 笔记已被标记为删除，不保存");
            return false;
        }
        
        // 如果是新笔记且内容为空，则不保存
        if (!existInDatabase() && TextUtils.isEmpty(mContent)) {
            Log.d(TAG, "isWorthSaving: 新笔记且内容为空，不保存");
            return false;
        }
        
        // 对于已存在的笔记，只要内容不为null就保存（即使内容为空字符串也保存）
        if (existInDatabase()) {
            if (mContent == null) {
                Log.d(TAG, "isWorthSaving: 笔记存在于数据库，但内容为null，不保存");
                return false;
            }
            
            // 不再检查mNote.isLocalModified()，确保内容总是被保存
            Log.d(TAG, "isWorthSaving: 笔记存在于数据库且内容不为null，允许保存");
            return true;
        }
        
        Log.d(TAG, "isWorthSaving: 笔记值得保存");
        return true;
    }

    public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
        mNoteSettingStatusListener = l;
    }

    public void setAlertDate(long date, boolean set) {
        if (date != mAlertDate) {
            mAlertDate = date;
            mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate));
        }
        if (mNoteSettingStatusListener != null) {
            mNoteSettingStatusListener.onClockAlertChanged(date, set);
        }
    }

    public void markDeleted(boolean mark) {
        mIsDeleted = mark;
        if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
                && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
                mNoteSettingStatusListener.onWidgetChanged();
        }
    }

    public void setBgColorId(int id) {
        if (id != mBgColorId) {
            mBgColorId = id;
            if (mNoteSettingStatusListener != null) {
                mNoteSettingStatusListener.onBackgroundColorChanged();
            }
            mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
        }
    }

    public void setCheckListMode(int mode) {
        if (mMode != mode) {
            if (mNoteSettingStatusListener != null) {
                mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
            }
            mMode = mode;
            mNote.setTextData(TextNote.MODE, String.valueOf(mMode));
        }
    }

    public void setWidgetType(int type) {
        if (type != mWidgetType) {
            mWidgetType = type;
            mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType));
        }
    }

    public void setWidgetId(int id) {
        if (id != mWidgetId) {
            mWidgetId = id;
            mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
        }
    }

    public void setWorkingText(String text) {
        // 记录传入的文本内容
        Log.d(TAG, "setWorkingText: 接收到文本, 长度=" + (text != null ? text.length() : 0) + 
              ", 内容=[" + (text != null ? (text.length() > 50 ? text.substring(0, 50) + "..." : text) : "null") + "]");
              
        // 确保text不为null
        if (text == null) {
            text = "";
            Log.w(TAG, "setWorkingText: 收到null文本，已转换为空字符串");
        }
        
        if (!TextUtils.equals(mContent, text)) {
            mContent = text;
            mNote.setTextData(DataColumns.CONTENT, mContent);
            
            // 记录设置后的结果
            Log.d(TAG, "setWorkingText: 已设置文本, 长度=" + mContent.length());
        } else {
            Log.d(TAG, "setWorkingText: 文本未变，不需更新");
        }
    }

    public void convertToCallNote(String phoneNumber, long callDate) {
        mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
        mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
        mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
    }

    public boolean hasClockAlert() {
        return (mAlertDate > 0 ? true : false);
    }

    public String getContent() {
        return mContent;
    }

    public long getAlertDate() {
        return mAlertDate;
    }

    public long getModifiedDate() {
        return mModifiedDate;
    }

    public int getBgColorResId() {
        return NoteBgResources.getNoteBgResource(mBgColorId);
    }

    public int getBgColorId() {
        return mBgColorId;
    }

    public int getTitleBgResId() {
        return NoteBgResources.getNoteTitleBgResource(mBgColorId);
    }

    public int getCheckListMode() {
        return mMode;
    }

    public long getNoteId() {
        return mNoteId;
    }

    public long getFolderId() {
        return mFolderId;
    }

    public int getWidgetId() {
        return mWidgetId;
    }

    public int getWidgetType() {
        return mWidgetType;
    }

    /**
     * 将笔记标记为已锁定或未锁定
     */
    public void setLocked(boolean locked, String passwordHash) {
        if (locked != mIsLocked || !passwordHash.equals(mPasswordHash)) {
            mIsLocked = locked;
            mPasswordHash = passwordHash;
            
            // 记录日志，确保锁定状态变化被记录
            Log.d("PasswordDebug", "WorkingNote.setLocked: 设置锁定状态 - ID=" + mNoteId + 
                  ", locked=" + locked + ", passwordHash=" + (passwordHash.isEmpty() ? "空" : "非空"));
            
            // 保存到数据库
            ContentValues values = new ContentValues();
            values.put(NoteColumns.IS_ENCRYPTED, locked ? 1 : 0);
            values.put(NoteColumns.PASSWORD_HASH, passwordHash);
            mContext.getContentResolver().update(Notes.CONTENT_NOTE_URI, values, 
                    NoteColumns.ID + "=?", new String[]{String.valueOf(mNoteId)});
            
            // 发送锁定状态变化通知
            if (mNoteSettingStatusListener != null) {
                mNoteSettingStatusListener.onLockStatusChanged(locked);
            }
        }
    }
    
    /**
     * 检查笔记是否已锁定
     */
    public boolean isLocked() {
        return mIsLocked;
    }
    
    /**
     * 获取笔记的密码哈希
     */
    public String getPasswordHash() {
        return mPasswordHash != null ? mPasswordHash : "";
    }

    /**
     * 强制同步笔记内容到数据表
     * 确保笔记内容被正确保存到数据库
     */
    public boolean syncNote() {
        if (mNoteId <= 0) {
            Log.w(TAG, "syncNote: 笔记ID无效，无法同步");
            return false;
        }
        
        Log.d(TAG, "syncNote: 开始同步笔记 - ID=" + mNoteId + 
              ", 内容长度=" + (mContent != null ? mContent.length() : 0));
        
        // 先确保数据已经设置
        if (mContent != null) {
            mNote.setTextData(DataColumns.CONTENT, mContent);
        }
        
        // 强制将数据同步到数据库
        boolean result = mNote.syncNote(mContext, mNoteId);
        
        Log.d(TAG, "syncNote: 同步结果=" + result + 
              ", ID=" + mNoteId + 
              ", 内容长度=" + (mContent != null ? mContent.length() : 0));
        
        return result;
    }

    public interface NoteSettingChangedListener {
        /**
         * Called when the background color of current note has just changed
         */
        void onBackgroundColorChanged();

        /**
         * Called when user set clock
         */
        void onClockAlertChanged(long date, boolean set);

        /**
         * Call when user create note from widget
         */
        void onWidgetChanged();

        /**
         * Call when switch between check list mode and normal mode
         * @param oldMode is previous mode before change
         * @param newMode is new mode
         */
        void onCheckListModeChanged(int oldMode, int newMode);
        
        /**
         * Call when note lock status changes
         * @param isLocked whether the note is locked
         */
        void onLockStatusChanged(boolean isLocked);
    }
}
