import Combine
import GRDB
import GRDBQuery

struct SegDenormRequest: Queryable {
    enum Ordering {
        case byScore
        case byName
    }

    var book: String

    // MARK: - Queryable Implementation
    
    static var defaultValue: [SegDenorm] { [] }
    
    func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[SegDenorm], Error> {
        ValueObservation
            .tracking(fetchValue(_:))
            .publisher(
                in: appDatabase.reader,
                scheduling: .immediate)
            .eraseToAnyPublisher()
    }
    
    func fetchValue(_ db: Database) throws -> [SegDenorm] {
        print("WOOOOOOF")
        var sql = "select seg_id as id, seg.book as book, group_concat(line.body, ';;') as body from seg join line on seg.line_id = line.rowid WHERE seg.book = 'bible.john' group by seg.seg_id"

        do {
            var ret =  try SegDenorm.fetchAll(db, sql: sql) // [Player]
            
        // print("SEGS DENORM")
        // print(ret)
        return ret
    } catch let error {
        print(error.localizedDescription)
        print(error)
        print("Error")
        return []
    }
        // if book == "" {
        //     return try Seg.filter(bookColumn ==  "bible.john")).fetchAll(db)
        // } else {
        //     return try Seg.filter(bookColumn ==  book).fetchAll(db)
        // }
        // switch ordering {
        // case .byScore:
        //     return try Seg.all().fetchAll(db)
        // case .byName:
        //     // return try Seg.all().orderedByName().fetchAll(db)
        //     return try Seg.all().fetchAll(db)
        // }
    }
}
