package com.all.pdfreader.pro.app.model

import com.all.pdfreader.pro.app.room.entity.PdfDocumentEntity

enum class SortField {
    NAME, DATE, SIZE
}

enum class SortDirection {
    ASC, DESC
}

data class SortConfig(
    val field: SortField,
    val direction: SortDirection
) {
    fun toPreferenceString(): String = "${field.name.lowercase()}_${direction.name.lowercase()}"
    
    companion object {
        fun fromPreferenceString(value: String): SortConfig {
            val parts = value.split("_")
            val field = SortField.valueOf(parts[0].uppercase())
            val direction = SortDirection.valueOf(parts[1].uppercase())
            return SortConfig(field, direction)
        }
        
        fun default(): SortConfig = SortConfig(SortField.DATE, SortDirection.DESC)
    }
    
    fun applySort(documents: List<PdfDocumentEntity>): List<PdfDocumentEntity> {
        return when (field) {
            SortField.NAME -> when (direction) {
                SortDirection.ASC -> documents.sortedBy { it.fileName.lowercase() }
                SortDirection.DESC -> documents.sortedByDescending { it.fileName.lowercase() }
            }
            SortField.DATE -> when (direction) {
                SortDirection.ASC -> documents.sortedBy { it.lastModified }
                SortDirection.DESC -> documents.sortedByDescending { it.lastModified }
            }
            SortField.SIZE -> when (direction) {
                SortDirection.ASC -> documents.sortedBy { it.fileSize }
                SortDirection.DESC -> documents.sortedByDescending { it.fileSize }
            }
        }
    }

    fun applySortFavorite(documents: List<PdfDocumentEntity>): List<PdfDocumentEntity> {
        return when (field) {
            SortField.NAME -> when (direction) {
                SortDirection.ASC -> documents.sortedBy { it.fileName.lowercase() }
                SortDirection.DESC -> documents.sortedByDescending { it.fileName.lowercase() }
            }
            SortField.DATE -> when (direction) {
                SortDirection.ASC -> documents.sortedBy { it.addedToFavoriteTime }
                SortDirection.DESC -> documents.sortedByDescending { it.addedToFavoriteTime }
            }
            SortField.SIZE -> when (direction) {
                SortDirection.ASC -> documents.sortedBy { it.fileSize }
                SortDirection.DESC -> documents.sortedByDescending { it.fileSize }
            }
        }
    }
}