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

import SwiftUI

struct ModalAddGameSeries : View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    
    @State var modalAddName : String = ""
    @State var modalGameSeriesCover : String?
    
    let defaultImage = UIImage()
    
    @State var isImportingCover = false
    
    var body: some View {
        NavigationView {
            Form {
                TextField("Name", text: $modalAddName)
                Image(uiImage: ICloudManager.imageFrom(path: self.modalGameSeriesCover) ?? defaultImage)
                    .resizable()
                    .frame(width:100, height: 100)

                Button(action: { self.isImportingCover = true}, label: { Text("Wähle Bild") })
            }
            .navigationBarTitle(Text("New Game Series"))
            .navigationBarItems(leading: Button(action: { self.presentationMode.wrappedValue.dismiss() }, label: {Text("Abbrechen")})
                //Add Button is disabled if no name is entered
                , trailing: Button(action: {
                    let gameSeries = GameSeries(context: CDManager.shared.viewContext)
                    gameSeries.name = self.modalAddName
                    gameSeries.cover_icloud_path = self.modalGameSeriesCover
                    
                    self.presentationMode.wrappedValue.dismiss()
            }) { Text("Fertig") }.disabled(self.modalAddName.trimmingCharacters(in: .whitespacesAndNewlines) == "" ))
            .fileImporter(
                isPresented: $isImportingCover,
                allowedContentTypes: [.jpeg, .png],
                allowsMultipleSelection: false
            ) { result in
                do {
                    let selectedFile : URL = try result.get().first!
                    
                    //It seems that isUbiquitousItem checks if the file is contained in the Apps iCloud folder
                    if (ICloudManager.inICloudContainer(url: selectedFile)) {
                        self.modalGameSeriesCover = ICloudManager.relativePathFrom(url: selectedFile)
                        
                        print("Selected Image in iCloud Path \(self.modalGameSeriesCover ?? "n/a")")
                    }else{
                        Alert(title: Text("Falscher Ordner"))
                        print("Außerhalb \(selectedFile.relativeString)")
                    }
                }catch{
                    print("GameSeriesEditView::body Error getting result '\(result)'")
                }
            }
            
        }
    }
}

struct GameSeriesAllView: View {
    @FetchRequest(entity: GameSeries.entity(), sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)])
    var gameSeries: FetchedResults<GameSeries>
    
    @State var showAddGameSeriesModal : Bool = false
    
    let defaultImage = UIImage()
    
    var body: some View {
        List(gameSeries) { game_series in
            NavigationLink(destination: GameSeriesLibraryView(gameSeries: game_series)) {
                HStack {
                    Image(uiImage: ICloudManager.imageFrom(path: game_series.cover_icloud_path) ?? defaultImage)
                        .resizable()
                        .frame(width:100, height: 75)
                    
                    VStack(alignment: .leading) {
                        Text(game_series.name ?? "n/a")
                            //Sonst wird der TExt kurioser Weise abgeschnitten wenn ein Bild davor ist. Hier nochmal später rein
                            //schauen
                            .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .leading)
                        Text("Spiele: \(game_series.games.filter({!($0 as! Game).inWishlist}).count ?? 0)/\(game_series.games.count ?? 0)").font(.caption)
                    }
                    
                }
            }
        }
        .padding()
        .navigationBarTitle(Text("Videospielserien"))
        .navigationBarItems(trailing:
            Button(action: {
                self.showAddGameSeriesModal = true
            }) {
                Image(systemName: "plus")
            })
        .sheet(isPresented: $showAddGameSeriesModal) {
            ModalAddGameSeries()
        }
    }
}
