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

import SwiftUI

struct GameDetailView : View {
    @ObservedObject var game : Game
    
    @State private var showDeleteAlert : Bool = false
    @State var hasFinishedDate : Bool = false
    @State var playthroughDate : Date = Date()
    

    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    
    @State var isImportingCover : Bool = false
    @State var isLent : Bool = false
    
    let defaultImage = UIImage()
    
    var gameSeriesPicker : some View {
        Text("TODO GameSeries Picker")
        /*Picker(selection: $game.gameSeries, label:
            Text("Spieleserie")
            , content: {
                Text("Keine").tag("")
                ForEach(gameSeriesStore.gameSeries) { gameSeries in
                    Text("\(gameSeries.name)").tag(gameSeries.id)
                }
        })*/
    }
    
    var body: some View {
        Form {
            Section {
                TextField("Videogame name", text: $game.name ?? "")
                
                //Gray color should indicate immutable data
                Text("\(game.console?.name ?? "No console")").foregroundColor(.gray)
                
                Toggle(isOn: $game.isDigital, label: {
                    Text("Nur Digital")
                })
                
                Toggle(isOn: $game.inWishlist, label: {
                    Text("In Wunschliste")
                })
                
                Toggle(isOn: $isLent, label: {
                    Text("Verliehen?")
                }).onReceive(game.objectWillChange) { _ in
                    self.isLent = self.game.lentTo != "";
                }.onAppear() {
                     self.isLent = self.game.lentTo != "";
                }
                
                if isLent {
                    TextField("Verliehen an", text: $game.lentTo ?? "")
                }
                
                gameSeriesPicker
                
                Toggle(isOn: $game.isFinished , label: {
                    Text("Durchgezockt")
                })
                
                if game.isFinished {
                    Toggle(isOn: $hasFinishedDate, label: {
                        Text("Gibts ein Datum")
                    })
                }
                
                if hasFinishedDate && game.isFinished {
                    DatePicker("Durchgezockt am",
                        selection: $playthroughDate,
                        in: ...Date(),
                        displayedComponents: [.date])
                }
            }
            
            Section {
                VStack{
                    Button("Neues Cover auswählen") {
                        self.isImportingCover = true
                    }
                    
                    Image(uiImage: ICloudManager.imageFrom(path: game.cover_icloud_path) ?? defaultImage)
                        .resizable()
                        .frame(width:100, height: 100)
                }
            }
            
            Section{
                gameDeleteButton
            }
            
        }
        .navigationBarTitle(Text("\(game.name ?? "N/A")"), displayMode: .automatic)
        .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)) {
                    game.cover_icloud_path = ICloudManager.relativePathFrom(url: selectedFile)
                    
                    print("Selected Image in iCloud Path \(game.cover_icloud_path ?? "n/a")")
                }else{
                    Alert(title: Text("Falscher Ordner"))
                    print("Außerhalb \(selectedFile.relativeString)")
                }
            }catch{
                print("ConsoleAllView::ModalAddConsoleToLibrary Error getting result '\(result)'")
            }
        }
    }
    
    //Irgendwie gibt es einen Bug der den Alert im navigationBarItem zwei mal aufruft.
    //Deswegen muss der delete Button is auf weiteres in die Form
    var gameDeleteButton : some View {
        Button(action: {
            self.showDeleteAlert = true
        }, label: {
            Spacer()
            Text("Spiel löschen")
            Spacer()
            //Image(systemName: "trash").foregroundColor(.red)
        })
        .accentColor(.red)
        .alert(isPresented: $showDeleteAlert, content: {
            Alert(title: Text("Aus Zockerhöhle entfernen"), message: Text("Willst du '\(self.game.name ?? "n/a")' wirklich aus der Zockerhöhle werfen?"), primaryButton: Alert.Button.destructive(Text("Ja!"), action: {

                //TZOOOODOOOOOO
                //self.gameVM.removeGame()
            }), secondaryButton: Alert.Button.cancel(Text("Lieber doch nicht")))
        })
    }
    
}
