import Combine
import GRDB
import GRDBQuery

/// A player request can be used with the `@Query` property wrapper in order to
/// feed a view with a list of players.
///
/// For example:
///
///     struct MyView: View {
///         @Query(SelectedRibbonRequest(ordering: .byName)) private var players: [SelectedRibbon]
///
///         var body: some View {
///             List(players) { player in ... )
///         }
///     }

struct SelectedRibbonRequest: Queryable {
    // enum Ordering {
    //     case byScore
    //     case byName
    // }

    /// The ordering used by the player request.
    // var ordering: Ordering
    static var defaultValue: [Ribbon] { [] }
    
    func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Ribbon], Error> {
        // Build the publisher from the general-purpose read-only access
        // granted by `appDatabase.reader`.
        // Some apps will prefer to call a dedicated method of `appDatabase`.
        ValueObservation
            .tracking(fetchValue(_:))
            .publisher(
                in: appDatabase.reader,
                // The `.immediate` scheduling feeds the view right on
                // subscription, and avoids an undesired animation when the
                // application starts.
                scheduling: .immediate)
            .eraseToAnyPublisher()
    }
    
    // This method is not required by Queryable, but it makes it easier
    func fetchValue(_ db: Database) throws -> [Ribbon] {

        // print("FETCH SELECTED RIBBON")
        // var ret2 =  try SelectedRibbon.fetchAll(db, sql: "SELECT * FROM selectedRibbon") // [Player]
        // print(ret2)

        // print("FETCH RIBBON")
        // var ret3 =  try Ribbon.fetchAll(db, sql: "SELECT * FROM Ribbon") // [Player]
        // print(ret3)



        // print("FETCH JOIN RIBBON")
        var ret =  try Ribbon.fetchAll(db, sql: "SELECT Ribbon.* FROM SelectedRibbon join Ribbon on SelectedRibbon.ribbonId = ribbon.rowId WHERE SelectedRibbon.rowId = 1") // [Player]
        // print(ret)
        return ret
    }
}
