//
//  GameSeriesDetailView.swift
//  Zockerhoehle
//
//  Created by Julian-Steffen Müller on 05.08.19.
//  Copyright © 2019 Julian-Steffen Müller. All rights reserved.
//

import SwiftUI
import CoreData

struct GameSeriesLibraryView: View {
    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest var games: FetchedResults<Game>
    
    @ObservedObject var gameSeries : GameSeries

    @State var isDetailActivated : Bool = false
    
    init(gameSeries : GameSeries) {
        self.gameSeries = gameSeries
        
        let gamesFR = NSFetchRequest<Game>(entityName: "Game")
        gamesFR.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
        gamesFR.predicate = NSPredicate(format: "series == %@", gameSeries)
        
        _games = FetchRequest(fetchRequest: gamesFR)
    }
    
    var body: some View {
        List(games) { game in
            NavigationLink(destination: GameDetailView(game: game)) {
                Text("\(game.name!)")
                
                if game.isDigital {
                    Image("digitalGame")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(height: 15)
                }
                
                if game.inWishlist  {
                    Image("wishlist")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(height: 15)
                }
            }
        }
        .navigationBarTitle(Text(self.gameSeries.name ?? "n/a"))
        .navigationBarItems(trailing:
                                NavigationLink(destination: GameSeriesEditView(gameSeries: self.gameSeries)) {
                Image(systemName: "pencil.and.ellipsis.rectangle")
            }
        )
        .padding()
    }
}
