//
//  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 GameSeriesPicker: View {
    @ObservedObject var game : Game
    
    @State private var selectedGameSeries = ""
    
    @FetchRequest(entity: GameSeries.entity(), sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)])
    var gameSeries: FetchedResults<GameSeries>

    var body: some View {
        Picker("Spieleserie", selection: $selectedGameSeries) {
            Text("Keine").tag("")
            ForEach(gameSeries) { game_series in
                Text(game_series.name ?? "n/a").tag(game_series.uuid.uuidString)
            }
        }.onChange(of: selectedGameSeries) { newValue in
            if let game_series = gameSeries.first(where: {$0.uuid.uuidString == newValue}) {
                if game.series != game_series {
                    game.series = game_series
                }
            }
        }
    }
    
    init(game : Game) {
        self.game = game
        
        if let game_series = game.series {
            _selectedGameSeries = State(initialValue: game_series.uuid.uuidString)
        }
    }
}

struct GameDetailView : View {
    @ObservedObject var game : Game
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    
    @State private var showDeleteAlert : Bool = false
    
    @State var isImportingCover : Bool = false
    
    let defaultImage = UIImage()
    
    @State var hasFinishedDate_raw : Bool = false
    private var hasFinishedDate: Binding<Bool> {
        Binding<Bool>(
            get: { self.hasFinishedDate_raw || self.game.finishedDate != .none },
            set: {
                hasFinishedDate_raw = $0
                if !$0 { self.game.finishedDate = .none }
            }
        )
    }
    
    @State var isLent_raw : Bool = false
    private var isLent: Binding<Bool> {
        Binding<Bool>(
            get: { self.isLent_raw || (self.game.lentTo != .none && self.game.lentTo != "") },
            set: {
                isLent_raw = $0
                if !$0 { self.game.lentTo = .none }
            }
        )
    }
    
    var finishedDateBinding: Binding<Date> {
        Binding<Date>(
            get: { self.game.finishedDate ?? Date() },
            set: { self.game.finishedDate = $0 })
    }
    
    var GameIsFinished : some View {
        Group {
            Toggle(isOn: $game.isFinished , label: {
                Text("Durchgezockt")
            })
            
            if game.isFinished {
                Toggle(isOn: hasFinishedDate, label: {
                    Text("Gibts ein Datum")
                })
            }
            
            if self.hasFinishedDate.wrappedValue && game.isFinished {
                DatePicker("Durchgezockt am",
                           selection: finishedDateBinding,
                           in: ...Date(),
                           displayedComponents: [.date])
            }
        }
    }
    
    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")
                })
                
                DatePicker("In Sammlung seit",
                           selection: $game.createdAt,
                           in: ...Date(),
                           displayedComponents: [.date])
                
                HStack {
                    Text("Anlass")
                        TextField("Anlass", text: $game.pickupDescription ?? "")
                }
                
                Toggle(isOn: $game.inWishlist, label: {
                    Text("In Wunschliste")
                })
                
                Toggle(isOn: isLent, label: {
                    Text("Verliehen?")
                })
                
                if isLent.wrappedValue {
                    TextField("Verliehen an", text: $game.lentTo ?? "")
                }
                
                GameSeriesPicker(game: game)
                
                GameIsFinished
            }
            
            Section {
                VStack{
                    Button("Neues Cover auswählen") {
                        self.isImportingCover = true
                    }
                    
                    Group {
                        Image(uiImage: ICloudManager.imageFrom(path: game.cover_icloud_path) ?? defaultImage)
                            .resizable()
                            .scaledToFit()
                    }.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")))
        })
    }
}
