package com.gallery.free.wallpaper.database

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

class FavorWpDbHelper(context: Context) :
    SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {

    companion object {
        const val DATABASE_VERSION = 2
        const val DATABASE_NAME = "FavoriteWallpapers.db"

        const val TABLE_NAME = "favorite_wallpapers"
        const val COLUMN_ID = "id"
        const val COLUMN_IMAGE_URL = "image_url"
        const val COLUMN_DESCRIPTION = "description"
        const val COLUMN_TIMESTAMP = "timestamp"
    }

    override fun onCreate(db: SQLiteDatabase) {
        val createTable = """
            CREATE TABLE $TABLE_NAME (
                $COLUMN_ID INTEGER PRIMARY KEY AUTOINCREMENT,
                $COLUMN_IMAGE_URL TEXT UNIQUE NOT NULL,
                $COLUMN_DESCRIPTION TEXT DEFAULT '', 
                $COLUMN_TIMESTAMP INTEGER DEFAULT (strftime('%s','now'))
            )
        """.trimIndent()
        db.execSQL(createTable)
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        if (oldVersion < 2) {
            db.execSQL("ALTER TABLE $TABLE_NAME ADD COLUMN $COLUMN_DESCRIPTION TEXT DEFAULT ''")
        }
    }

    // 添加壁纸到收藏
    fun addFavorite(imageUrl: String, description: String = ""): Boolean {
        val db = writableDatabase
        val values = ContentValues().apply {
            put(COLUMN_IMAGE_URL, imageUrl)
            if (description.isNotEmpty()) {
                put(COLUMN_DESCRIPTION, description)
            }
        }

        return try {
            val result = db.insertWithOnConflict(
                TABLE_NAME,
                null,
                values,
                SQLiteDatabase.CONFLICT_IGNORE
            )
            result != -1L
        } catch (e: Exception) {
            false
        } finally {
            db.close()
        }
    }

    // 更新已存在的收藏信息（更新描述）
    fun updateFavoriteDescription(imageUrl: String, description: String): Boolean {
        val db = writableDatabase
        val values = ContentValues().apply {
            put(COLUMN_DESCRIPTION, description)
        }

        return try {
            val result = db.update(
                TABLE_NAME,
                values,
                "$COLUMN_IMAGE_URL = ?",
                arrayOf(imageUrl)
            )
            result > 0
        } catch (e: Exception) {
            false
        } finally {
            db.close()
        }
    }

    // 从收藏中移除壁纸
    fun removeFavorite(imageUrl: String): Boolean {
        val db = writableDatabase
        return try {
            val result = db.delete(
                TABLE_NAME,
                "$COLUMN_IMAGE_URL = ?",
                arrayOf(imageUrl)
            )
            result > 0
        } catch (e: Exception) {
            false
        } finally {
            db.close()
        }
    }

    // 检查壁纸是否在收藏中
    fun isFavorite(imageUrl: String): Boolean {
        val db = readableDatabase
        var cursor: Cursor? = null

        return try {
            cursor = db.query(
                TABLE_NAME,
                arrayOf(COLUMN_IMAGE_URL),
                "$COLUMN_IMAGE_URL = ?",
                arrayOf(imageUrl),
                null, null, null
            )
            cursor?.count ?: 0 > 0
        } catch (e: Exception) {
            false
        } finally {
            cursor?.close()
            db.close()
        }
    }

    data class FavoriteInfo(
        val imageUrl: String,
        val description: String
    )

    // 获取所有收藏的壁纸信息（URL和描述）
    fun getAllFavoritesWithInfo(): List<FavoriteInfo> {
        val db = readableDatabase
        val favorites = mutableListOf<FavoriteInfo>()
        var cursor: Cursor? = null

        try {
            cursor = db.query(
                TABLE_NAME,
                arrayOf(COLUMN_IMAGE_URL, COLUMN_DESCRIPTION),
                null, null, null, null,
                "$COLUMN_TIMESTAMP DESC"
            )

            cursor?.let {
                val urlIndex = it.getColumnIndex(COLUMN_IMAGE_URL)
                val descIndex = it.getColumnIndex(COLUMN_DESCRIPTION)
                while (it.moveToNext()) {
                    if (urlIndex != -1) {
                        val url = it.getString(urlIndex)
                        val description = if (descIndex != -1) it.getString(descIndex) else ""
                        favorites.add(FavoriteInfo(url, description))
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            cursor?.close()
            db.close()
        }

        return favorites
    }

    // 获取所有收藏的壁纸URL（保持向后兼容）
    fun getAllFavorites(): List<String> {
        val db = readableDatabase
        val favorites = mutableListOf<String>()
        var cursor: Cursor? = null

        try {
            cursor = db.query(
                TABLE_NAME,
                arrayOf(COLUMN_IMAGE_URL),
                null, null, null, null,
                "$COLUMN_TIMESTAMP DESC"
            )

            cursor?.let {
                val urlIndex = it.getColumnIndex(COLUMN_IMAGE_URL)
                while (it.moveToNext()) {
                    if (urlIndex != -1) {
                        favorites.add(it.getString(urlIndex))
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            cursor?.close()
            db.close()
        }

        return favorites
    }

    // 获取收藏数量
    fun getFavoriteCount(): Int {
        val db = readableDatabase
        var cursor: Cursor? = null

        return try {
            cursor = db.rawQuery("SELECT COUNT(*) FROM $TABLE_NAME", null)
            if (cursor?.moveToFirst() == true) {
                cursor.getInt(0)
            } else {
                0
            }
        } catch (e: Exception) {
            0
        } finally {
            cursor?.close()
            db.close()
        }
    }

    // 检查是否有指定URL的收藏
    fun hasFavorite(imageUrl: String): Boolean {
        return isFavorite(imageUrl)
    }

    // 批量获取收藏状态
    fun getFavoriteStatus(urls: List<String>): Map<String, Boolean> {
        val db = readableDatabase
        val result = mutableMapOf<String, Boolean>()
        var cursor: Cursor? = null

        try {
            // 为每个URL创建一个占位符
            val placeholders = urls.joinToString(",") { "?" }
            val query = """
                SELECT $COLUMN_IMAGE_URL 
                FROM $TABLE_NAME 
                WHERE $COLUMN_IMAGE_URL IN ($placeholders)
            """.trimIndent()

            cursor = db.rawQuery(query, urls.toTypedArray())

            while (cursor?.moveToNext() == true) {
                val urlIndex = cursor.getColumnIndex(COLUMN_IMAGE_URL)
                if (urlIndex != -1) {
                    result[cursor.getString(urlIndex)] = true
                }
            }

            // 设置不在结果中的URL为false
            urls.forEach { url ->
                if (!result.containsKey(url)) {
                    result[url] = false
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            cursor?.close()
            db.close()
        }

        return result
    }
}