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

import SwiftUI
import CoreData
//extension String: Identifiable {
//    public var id: String {
//        return self
//    }
//}

struct SettingsView: View {
    @State var backupImportFileIndex = -1
    @State var backupImportUpdateExistingEntrys = false
    @State var importFiles : [String] = LibraryImport().backupFiles()
    
    @FetchRequest(entity: Game.entity(), sortDescriptors: [])
    var games: FetchedResults<Game>
    
    @FetchRequest(entity: Accessory.entity(), sortDescriptors: [])
    var accessories: FetchedResults<Accessory>
    
    @FetchRequest(entity: Console.entity(), sortDescriptors: [])
    var consoles: FetchedResults<Console>
    
    @FetchRequest(entity: GameSeries.entity(), sortDescriptors: [])
    var gameSeries: FetchedResults<GameSeries>
    
    func exportLibrary() {
        // There is currently no way to directly convert FetchesResults to array.
        // Maybe I should do an Fetchesresulsts Extension
        var exportGames : [Game] = []
        games.forEach {exportGames.append($0)}
        var exportAccessories : [Accessory] = []
        accessories.forEach {exportAccessories.append($0)}
        var exportConsoles : [Console] = []
        consoles.forEach {exportConsoles.append($0)}
        var exportGameSeries : [GameSeries] = []
        gameSeries.forEach {exportGameSeries.append($0)}
        
        let libExport = LibraryExporter(games: exportGames, consoles: exportConsoles, gameSeries: exportGameSeries, accessories: exportAccessories)
        
        libExport.export(name: Date().formattedInTimeZone())
        importFiles = LibraryImport().backupFiles()
    }
    
    fileprivate func deleteLibrary() {
        games.forEach{CDManager.shared.viewContext.delete($0)}
        accessories.forEach{CDManager.shared.viewContext.delete($0)}
        consoles.forEach{CDManager.shared.viewContext.delete($0)}
        gameSeries.forEach{CDManager.shared.viewContext.delete($0)}
    }
    
    @State var showDeletionAlert : Bool = false
    var body: some View {
        Form {
            Section(header: Text("Backup")) {
                Button(action: { self.exportLibrary() }, label: { Text("Bärenhöhle sichern!") })

                Picker(selection: $backupImportFileIndex, label: Text("Choose Backup")) {
                        Text("None").tag(-1)
                        ForEach(0 ..< (importFiles.count), id: \.self) {
                            Text(LibraryImport.backupName(from: self.importFiles[$0]) ?? "n/a").tag($0)
                        }.navigationBarTitle("Backups")
                }
                Toggle("Ja, Ich will alles zurücksetzen", isOn: $backupImportUpdateExistingEntrys)
                Button(action: {
                    deleteLibrary()
                    LibraryImport().importLIB(from: self.importFiles[self.backupImportFileIndex])
                }, label: { Text("Reset & Import") }).disabled(backupImportFileIndex < 0 || !backupImportUpdateExistingEntrys)
                Button(action: {
                    deleteLibrary()
                }, label: { Text("Nur Reset") }).disabled(!backupImportUpdateExistingEntrys)
            }
        }.navigationBarTitle("Einstellungen")
        
    }
}
