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

import SwiftUI

struct ConsoleEditView: View {
    @ObservedObject var console : Console
    
    @State var isImportingLogo : Bool = false
    let defaultImage = UIImage()
    
    var body: some View {
        Form {
            TextField("Name der Konsole", text: $console.name)
            TextField("Abkürzung", text: $console.shortName ?? "")
            TextField("Hersteller", text: $console.manufacturer ?? "")
            DatePicker(selection: $console.releaseDate, in: ...Date(), displayedComponents: .date) {
                Text("Erscheinungsjahr")
            }
            
            Image(uiImage: ICloudManager.imageFrom(path: self.console.logo_icloud_path) ?? defaultImage)
                .resizable()
                .frame(width:100, height: 100)
            
            Button(action: { self.isImportingLogo = true }, label: { Text("Pick Image") })
        }
        .navigationBarTitle("Editiere Konsole")
        .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)) {
                    console.logo_icloud_path = ICloudManager.relativePathFrom(url: selectedFile)
                    
                    print("Selected Image in iCloud Path \(console.logo_icloud_path ?? "n/a")")
                }else{
                    Alert(title: Text("Falscher Ordner"))
                    print("Außerhalb \(selectedFile.relativeString)")
                }
            }catch{
                print("ConsoleAllView::ModalAddConsoleToLibrary Error getting result '\(result)'")
            }
        }
    }
}
