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

import Foundation
import SwiftUI
import QGrid

struct ModalAddConsoleToLibrary : View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    @Environment(\.managedObjectContext) private var viewContext
    
    @State var modalConsoleName : String = ""
    @State var modalConsoleLogoICloudPath : String? = .none
    @State var modalConsoleShortName : String = ""
    @State var modalConsoleManufacturer : String = ""
    @State var modalConsoleReleaseDate : Date = Date()
    @State var isImportingLogo : Bool = false
    
    let defaultImage = UIImage()
    
    var addButton : some View {
        return Button(action: {
                        let console = Console(context: viewContext)
                        console.name = modalConsoleName
                        console.shortName = modalConsoleShortName
                        console.manufacturer = modalConsoleManufacturer
                        console.releaseDate = modalConsoleReleaseDate
                        
                        console.logo_icloud_path = self.modalConsoleLogoICloudPath
                        
                        self.presentationMode.wrappedValue.dismiss()},
                      label: { Text("Fertig") })
                .disabled(self.modalConsoleName.trimmingCharacters(in: .whitespacesAndNewlines) == "" )
    }
    
    var body: some View {
        NavigationView {
            Form {
                TextField("Name", text: $modalConsoleName)
                TextField("Abkürzung", text: $modalConsoleShortName)
                TextField("Hersteller", text: $modalConsoleManufacturer)
                DatePicker(selection: $modalConsoleReleaseDate, in: ...Date(), displayedComponents: .date) {
                    Text("Erscheinungsjahr")
                }
                Image(uiImage: ICloudManager.imageFrom(path: self.modalConsoleLogoICloudPath) ?? defaultImage)
                    .resizable()
                    .scaledToFit()
                Button(action: {
                    isImportingLogo = true;
                }, label: { Text("Bla")})
            }
            .font(.caption)
            .navigationBarTitle(Text("Neue Konsole anlegen"))
            .navigationBarItems(leading: Button(action: { self.presentationMode.wrappedValue.dismiss() },
                                                label: {Text("Abbrechen")}),
                                //Add Button is disabled if no name is entered
                                trailing: addButton)
            .navigationViewStyle(StackNavigationViewStyle())
            .fileImporter(
                isPresented: $isImportingLogo,
                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.modalConsoleLogoICloudPath = ICloudManager.relativePathFrom(url: selectedFile)
                        
                        print("Selected Image in iCloud Path \(self.modalConsoleLogoICloudPath ?? "n/a")")
                    }else{
                        Alert(title: Text("Falscher Ordner"))
                        print("Außerhalb \(selectedFile.relativeString)")
                    }
                }catch{
                    print("ConsoleAllView::ModalAddConsoleToLibrary Error getting result '\(result)'")
                }
            }
        }
    }
}

struct ConsolesListView : View {
    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(entity: Console.entity(), sortDescriptors: [NSSortDescriptor(key: "manufacturer", ascending: true), NSSortDescriptor(key: "generation", ascending: true), NSSortDescriptor(key: "name", ascending: true)])
    var consoles: FetchedResults<Console>
    
    @State var showAddConsoleToLibraryModal: Bool = false
    
    var body: some View {
        QGrid(consoles, columns: 4, columnsInLandscape: 6) {
            GridCell(console: $0)
         }
        .padding()
        .navigationBarTitle(Text("Zockerhöhle"))
        .navigationBarItems(trailing:
            Button(action: {
                self.showAddConsoleToLibraryModal = true
            }) {
                Image(systemName: "plus")
            })
        .sheet(isPresented: $showAddConsoleToLibraryModal) {
            ModalAddConsoleToLibrary()
        }
    }
}

struct GridCell: View {
    var console: Console
    let defaultImage = UIImage()
    
    var body: some View {
        VStack() {
            if ICloudManager.fileExists(at: console.logo_icloud_path) {
                NavigationLink(destination: ConsoleLibraryView(console: console)) {
                    VStack {
                        Image(uiImage: ICloudManager.imageFrom(path: console.logo_icloud_path) ?? defaultImage)
                        .resizable()
                        .scaledToFit()
                        //.shadow(color: .primary, radius: 5)
                        .padding([.horizontal, .top], 7)
                        Text(console.shortName ?? console.name!).lineLimit(1)
                    }
                }.buttonStyle(PlainButtonStyle())
                
            }else{
                NavigationLink(destination: ConsoleLibraryView(console: console)) {
                    Text(console.shortName ?? console.name!)
                }
            }
        }
    }
}
