package net.micode.notes.data;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class PrivacyPasswordManager {
    private static final String TABLE_NAME = "privacy_password";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_PASSWORD = "password";
    private static final String COLUMN_CREATED_DATE = "created_date";

    private NotesDatabaseHelper mDbHelper;
    private Context mContext;

    public PrivacyPasswordManager(Context context) {
        mContext = context;
        mDbHelper = NotesDatabaseHelper.getInstance(context);
    }

    /**
     * 设置隐私密码
     * @param password 密码
     * @return 是否设置成功
     */
    public boolean setPassword(String password) {
        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_PASSWORD, password);
        
        // 先删除旧的密码
        db.delete(TABLE_NAME, null, null);
        
        // 插入新密码
        long result = db.insert(TABLE_NAME, null, values);
        return result != -1;
    }

    /**
     * 验证密码是否正确
     * @param password 要验证的密码
     * @return 密码是否正确
     */
    public boolean verifyPassword(String password) {
        SQLiteDatabase db = mDbHelper.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME, new String[]{COLUMN_PASSWORD}, null, null, null, null, null);
        
        if (cursor != null && cursor.moveToFirst()) {
            String storedPassword = cursor.getString(cursor.getColumnIndex(COLUMN_PASSWORD));
            cursor.close();
            return storedPassword.equals(password);
        }
        
        if (cursor != null) {
            cursor.close();
        }
        return false;
    }

    /**
     * 检查是否已设置密码
     * @return 是否已设置密码
     */
    public boolean hasPassword() {
        SQLiteDatabase db = mDbHelper.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME, new String[]{COLUMN_ID}, null, null, null, null, null);
        boolean hasPassword = cursor != null && cursor.getCount() > 0;
        if (cursor != null) {
            cursor.close();
        }
        return hasPassword;
    }
} 