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.Chapter;
import net.micode.myapplication.model.Course;

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

public class CourseRepository {
    private DatabaseHelper dbHelper;

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

    // Course相关操作
    public long insertCourse(Course course) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_COURSE_ID, course.getCourseId());
        values.put(DatabaseHelper.COLUMN_COURSE_NAME, course.getCourseName());
        values.put(DatabaseHelper.COLUMN_SCHOOL, course.getSchool());

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

    public Course getCourseById(String courseId) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(DatabaseHelper.TABLE_COURSES,
                null,
                DatabaseHelper.COLUMN_COURSE_ID + " = ?",
                new String[]{courseId},
                null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            Course course = new Course();
            course.setCourseId(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_COURSE_ID)));
            course.setCourseName(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_COURSE_NAME)));
            course.setSchool(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_SCHOOL)));
            cursor.close();
            return course;
        }

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

    public List<Course> getAllCourses() {
        List<Course> courses = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(DatabaseHelper.TABLE_COURSES, null, null, null, null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            do {
                Course course = new Course();
                course.setCourseId(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_COURSE_ID)));
                course.setCourseName(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_COURSE_NAME)));
                course.setSchool(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_SCHOOL)));
                courses.add(course);
            } while (cursor.moveToNext());
            cursor.close();
        }

        return courses;
    }

    // Chapter相关操作
    public long insertChapter(Chapter chapter) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_CHAPTER_ID, chapter.getChapterId());
        values.put(DatabaseHelper.COLUMN_COURSE_ID, chapter.getCourseId());
        values.put(DatabaseHelper.COLUMN_CHAPTER_NUMBER, chapter.getChapterNumber());
        values.put(DatabaseHelper.COLUMN_CHAPTER_TITLE, chapter.getChapterTitle());
        values.put(DatabaseHelper.COLUMN_KEYWORDS, listToString(chapter.getKeywords()));
        values.put(DatabaseHelper.COLUMN_ALIASES, listToString(chapter.getAliases()));

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

    public Chapter getChapterById(String chapterId) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(DatabaseHelper.TABLE_CHAPTERS,
                null,
                DatabaseHelper.COLUMN_CHAPTER_ID + " = ?",
                new String[]{chapterId},
                null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            Chapter chapter = new Chapter();
            chapter.setChapterId(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_CHAPTER_ID)));
            chapter.setCourseId(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_COURSE_ID)));
            chapter.setChapterNumber(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_CHAPTER_NUMBER)));
            chapter.setChapterTitle(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_CHAPTER_TITLE)));
            chapter.setKeywords(stringToList(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_KEYWORDS))));
            chapter.setAliases(stringToList(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ALIASES))));
            cursor.close();
            return chapter;
        }

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

    public List<Chapter> getChaptersByCourseId(String courseId) {
        List<Chapter> chapters = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(DatabaseHelper.TABLE_CHAPTERS,
                null,
                DatabaseHelper.COLUMN_COURSE_ID + " = ?",
                new String[]{courseId},
                null, null, DatabaseHelper.COLUMN_CHAPTER_NUMBER + " ASC");

        if (cursor != null && cursor.moveToFirst()) {
            do {
                Chapter chapter = new Chapter();
                chapter.setChapterId(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_CHAPTER_ID)));
                chapter.setCourseId(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_COURSE_ID)));
                chapter.setChapterNumber(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_CHAPTER_NUMBER)));
                chapter.setChapterTitle(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_CHAPTER_TITLE)));
                chapter.setKeywords(stringToList(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_KEYWORDS))));
                chapter.setAliases(stringToList(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ALIASES))));
                chapters.add(chapter);
            } while (cursor.moveToNext());
            cursor.close();
        }

        return chapters;
    }

    public List<Chapter> getAllChapters() {
        List<Chapter> chapters = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(DatabaseHelper.TABLE_CHAPTERS, null, null, null, null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            do {
                Chapter chapter = new Chapter();
                chapter.setChapterId(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_CHAPTER_ID)));
                chapter.setCourseId(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_COURSE_ID)));
                chapter.setChapterNumber(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_CHAPTER_NUMBER)));
                chapter.setChapterTitle(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_CHAPTER_TITLE)));
                chapter.setKeywords(stringToList(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_KEYWORDS))));
                chapter.setAliases(stringToList(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ALIASES))));
                chapters.add(chapter);
            } while (cursor.moveToNext());
            cursor.close();
        }

        return chapters;
    }

    // 批量插入课程和章节数据
    public void insertCourseWithChapters(Course course, List<Chapter> chapters) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            insertCourse(course);
            for (Chapter chapter : chapters) {
                insertChapter(chapter);
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }

    // 辅助方法：将List转换为String（用逗号分隔）
    private String listToString(List<String> list) {
        if (list == null || list.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (i > 0) {
                sb.append(",");
            }
            sb.append(list.get(i));
        }
        return sb.toString();
    }

    // 辅助方法：将String转换为List
    private List<String> stringToList(String str) {
        List<String> list = new ArrayList<>();
        if (str != null && !str.trim().isEmpty()) {
            String[] items = str.split(",");
            for (String item : items) {
                if (!item.trim().isEmpty()) {
                    list.add(item.trim());
                }
            }
        }
        return list;
    }

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