package net.micode.myapplication.repository;

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

import net.micode.myapplication.database.DatabaseHelper;
import net.micode.myapplication.model.Note;

import java.util.ArrayList;
import java.util.List;

public class NoteRepository {
    private DatabaseHelper dbHelper;

    public NoteRepository(Context context) {
        this.dbHelper = new DatabaseHelper(context);
    }

    public long insertNote(Note note) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_NOTE_ID, note.getNoteId());
        values.put(DatabaseHelper.COLUMN_TITLE, note.getTitle());
        values.put(DatabaseHelper.COLUMN_DESCRIPTION, note.getDescription());
        values.put(DatabaseHelper.COLUMN_OCR_TEXT, note.getOcrText());
        values.put(DatabaseHelper.COLUMN_COURSE_ID, note.getCourseId());
        values.put(DatabaseHelper.COLUMN_CHAPTER_ID, note.getChapterId());
        values.put(DatabaseHelper.COLUMN_FILE_PATH, note.getFilePath());
        values.put(DatabaseHelper.COLUMN_UPLOAD_TIME, note.getUploadTime());
        values.put(DatabaseHelper.COLUMN_UPDATE_TIME, note.getUpdateTime());

        return db.insert(DatabaseHelper.TABLE_NOTES, null, values);
    }

    public Note getNoteById(String noteId) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(DatabaseHelper.TABLE_NOTES,
                null,
                DatabaseHelper.COLUMN_NOTE_ID + " = ?",
                new String[]{noteId},
                null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            Note note = cursorToNote(cursor);
            cursor.close();
            return note;
        }

        if (cursor != null) {
            cursor.close();
        }
        return null;
    }

    public List<Note> getAllNotes() {
        List<Note> notes = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(DatabaseHelper.TABLE_NOTES, null, null, null, null, null, 
                DatabaseHelper.COLUMN_UPLOAD_TIME + " DESC");

        if (cursor != null && cursor.moveToFirst()) {
            do {
                notes.add(cursorToNote(cursor));
            } while (cursor.moveToNext());
            cursor.close();
        }

        return notes;
    }

    public List<Note> getNotesByCourse(String courseId) {
        List<Note> notes = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(DatabaseHelper.TABLE_NOTES,
                null,
                DatabaseHelper.COLUMN_COURSE_ID + " = ?",
                new String[]{courseId},
                null, null, DatabaseHelper.COLUMN_UPLOAD_TIME + " DESC");

        if (cursor != null && cursor.moveToFirst()) {
            do {
                notes.add(cursorToNote(cursor));
            } while (cursor.moveToNext());
            cursor.close();
        }

        return notes;
    }

    public List<Note> getNotesByChapter(String chapterId) {
        List<Note> notes = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(DatabaseHelper.TABLE_NOTES,
                null,
                DatabaseHelper.COLUMN_CHAPTER_ID + " = ?",
                new String[]{chapterId},
                null, null, DatabaseHelper.COLUMN_UPLOAD_TIME + " DESC");

        if (cursor != null && cursor.moveToFirst()) {
            do {
                notes.add(cursorToNote(cursor));
            } while (cursor.moveToNext());
            cursor.close();
        }

        return notes;
    }

    public int updateNote(Note note) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_TITLE, note.getTitle());
        values.put(DatabaseHelper.COLUMN_DESCRIPTION, note.getDescription());
        values.put(DatabaseHelper.COLUMN_OCR_TEXT, note.getOcrText());
        values.put(DatabaseHelper.COLUMN_COURSE_ID, note.getCourseId());
        values.put(DatabaseHelper.COLUMN_CHAPTER_ID, note.getChapterId());
        values.put(DatabaseHelper.COLUMN_FILE_PATH, note.getFilePath());
        values.put(DatabaseHelper.COLUMN_UPDATE_TIME, System.currentTimeMillis());

        return db.update(DatabaseHelper.TABLE_NOTES, values,
                DatabaseHelper.COLUMN_NOTE_ID + " = ?",
                new String[]{note.getNoteId()});
    }

    public int deleteNote(String noteId) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        return db.delete(DatabaseHelper.TABLE_NOTES,
                DatabaseHelper.COLUMN_NOTE_ID + " = ?",
                new String[]{noteId});
    }

    public int deleteNotesByCourse(String courseId) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        return db.delete(DatabaseHelper.TABLE_NOTES,
                DatabaseHelper.COLUMN_COURSE_ID + " = ?",
                new String[]{courseId});
    }

    private Note cursorToNote(Cursor cursor) {
        Note note = new Note();
        note.setNoteId(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_NOTE_ID)));
        note.setTitle(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_TITLE)));
        note.setDescription(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_DESCRIPTION)));
        note.setOcrText(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_OCR_TEXT)));
        note.setCourseId(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_COURSE_ID)));
        note.setChapterId(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_CHAPTER_ID)));
        note.setFilePath(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_FILE_PATH)));
        note.setUploadTime(cursor.getLong(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_UPLOAD_TIME)));
        note.setUpdateTime(cursor.getLong(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_UPDATE_TIME)));
        return note;
    }

    // 搜索笔记
    public List<Note> searchNotes(String query) {
        List<Note> notes = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        
        String selection = DatabaseHelper.COLUMN_TITLE + " LIKE ? OR " +
                          DatabaseHelper.COLUMN_DESCRIPTION + " LIKE ? OR " +
                          DatabaseHelper.COLUMN_OCR_TEXT + " LIKE ?";
        String[] selectionArgs = new String[]{"%" + query + "%", "%" + query + "%", "%" + query + "%"};
        
        Cursor cursor = db.query(DatabaseHelper.TABLE_NOTES,
                null, selection, selectionArgs, null, null,
                DatabaseHelper.COLUMN_UPLOAD_TIME + " DESC");

        if (cursor != null && cursor.moveToFirst()) {
            do {
                notes.add(cursorToNote(cursor));
            } while (cursor.moveToNext());
            cursor.close();
        }

        return notes;
    }

    // 关闭数据库连接
    public void close() {
        dbHelper.close();
    }
}