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

import SwiftUI
import CoreData

struct ModalAddToConsoleLibrary : View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    
    @State var modalAddName : String = ""
    @State var modalAddToWishlist : Bool
    @State var modalIsDigital : Bool = false
    
    @State var isVideogamesSelected : Bool
    
    var console : Console;
    
    private func addGameToLibrary() {
        let game = Game(context: CDManager.shared.viewContext)
        game.name = self.modalAddName
        game.console = self.console;
        game.inWishlist = self.modalAddToWishlist
        game.isDigital = self.modalIsDigital
    }
    
    private func addAccessoryToLibrary() {
        let accessory = Accessory(context: CDManager.shared.viewContext)
        accessory.name = self.modalAddName
        accessory.console = self.console
        accessory.inWishlist = self.modalAddToWishlist
    }
    
    var addButton : some View {
        return Button(action: {
                            if (self.isVideogamesSelected) {
                                self.addGameToLibrary()
                                
                            }else{
                                self.addAccessoryToLibrary()
                            }
                            self.presentationMode.wrappedValue.dismiss()},
                      label: { Text("Fertig") })
                .disabled(self.modalAddName.trimmingCharacters(in: .whitespacesAndNewlines) == "" )
    }
    
    var body: some View {
        NavigationView {
            Form {
                TextField("Name", text: $modalAddName)
                if self.isVideogamesSelected {
                    Toggle(isOn: $modalIsDigital, label: {
                        Text("Ist Digital")
                    })
                }
                Toggle(isOn: $modalAddToWishlist, label: {
                    Text("Auf die Wunschliste")
                })
            }
            .font(.caption)
            .navigationBarTitle(self.isVideogamesSelected ? Text("Spiel hinzufügen") :  Text("Zubehör hinzufügen"))
            .navigationBarItems(leading: Button(action: { self.presentationMode.wrappedValue.dismiss() },
                                                label: {Text("Abbrechen")}),
                                //Add Button is disabled if no name is entered
                                trailing: addButton)
            .navigationViewStyle(StackNavigationViewStyle())
        }
    }
}

struct ConsoleLibraryView : View {
    @ObservedObject var console : Console
    
    @Environment(\.managedObjectContext) private var viewContext
    
    var gamesFetchRequest: FetchRequest<Game>
    var games: FetchedResults<Game> { gamesFetchRequest.wrappedValue }
    
    var accessoryFetchRequest: FetchRequest<Accessory>
    var accessories: FetchedResults<Accessory> { accessoryFetchRequest.wrappedValue }
    
    @State var isVideogamesSelected = true
    @State var showWishlist = false
    @State var showAddToConsoleLibraryModal: Bool = false
    
    init (console: Console) {
        self.console = console
        
        self.gamesFetchRequest = FetchRequest<Game>(entity: Game.entity(), sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)], predicate: NSPredicate(format: "console == %@", console))
        
        self.accessoryFetchRequest = FetchRequest<Accessory>(entity: Accessory.entity(), sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)], predicate: NSPredicate(format: "console == %@", console))
    }
    
    let columns : [GridItem] = [
        GridItem(.adaptive(minimum: 100))
    ]
    
    let defaultImage = UIImage()
    
    var body: some View {
        VStack {
            HStack {
                Spacer()
                Picker("Options", selection: $isVideogamesSelected) {
                    Text("Videogames").tag(true)
                    Text("Accessories").tag(false)

                }.pickerStyle(SegmentedPickerStyle())
                Spacer()
            }
            if self.isVideogamesSelected {
                ScrollView {
                    LazyVGrid(columns: columns, spacing: 20) {
                        ForEach(games.filter({$0.inWishlist == self.showWishlist})) { game in
                            NavigationLink(destination: GameDetailView(game: game)) {
                                if ICloudManager.fileExists(at: game.cover_icloud_path) {
                                    Image(uiImage: ICloudManager.imageFrom(path: game.cover_icloud_path) ?? defaultImage)
                                        .resizable()
                                        .scaledToFit()
                                        .cornerRadius(5)
                                }else{
                                    Group {
                                        Text(game.name)
                                            .font(.caption)
                                            .foregroundColor(Color.black)
                                            .padding()
                                            .multilineTextAlignment(.center)
                                    }
                                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                                    .background(Color.gray)
                                    .cornerRadius(5)
                                }
                                
                                
//                                if game.isDigital {
//                                    Image("digitalGame")
//                                    .resizable()
//                                    .aspectRatio(contentMode: .fit)
//                                    .frame(height: 15)
//                                }
                            }
                        }
                    }.padding()
                }
            }else {
                List(accessories.filter({$0.inWishlist == self.showWishlist})) {accessory in
                    NavigationLink(destination: AccessoryDetailView(accessory: accessory)) {
                        Text("\(accessory.name)")
                    }
                }
            }
        }
        .navigationBarTitle(Text("\(self.console.name ?? "n/a")"), displayMode: .automatic)
        .navigationBarItems(trailing:
            HStack {
                NavigationLink(destination: ConsoleEditView(console: self.console)) {
                    Image(systemName: "pencil.and.ellipsis.rectangle")
                }

                Button(action: { self.showAddToConsoleLibraryModal = true },
                       label: { Image(systemName: "plus")})
                    .padding(5)
                
                Button(action: { self.showWishlist.toggle()},
                       label: { Image("wishlist")
                                    .resizable()
                                    .aspectRatio(contentMode: .fit)
                        })
                    .accentColor(self.showWishlist ?  Color.red : Color.blue)
            })
        .sheet(isPresented: $showAddToConsoleLibraryModal) {
            ModalAddToConsoleLibrary(modalAddToWishlist: self.showWishlist, isVideogamesSelected: self.isVideogamesSelected, console: self.console)
        }
    }
}
