//
//  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()
    
    func exportLibrary() {
        do {
            let gamesFR = NSFetchRequest<Game>(entityName: "Game")
            let consolesFR = NSFetchRequest<Console>(entityName: "Console")
            let gameSeriesFR = NSFetchRequest<GameSeries>(entityName: "GameSeries")
            let accessoriesFR = NSFetchRequest<Accessory>(entityName: "Accessory")
            
            let games = try CDManager.shared.viewContext.fetch(gamesFR)
            let consoles = try CDManager.shared.viewContext.fetch(consolesFR)
            let gameSeries = try CDManager.shared.viewContext.fetch(gameSeriesFR)
            let accessories = try CDManager.shared.viewContext.fetch(accessoriesFR)
            
            let libExport = LibraryExporter(games: games, consoles: consoles, gameSeries: gameSeries, accessories: accessories)
            
            libExport.export(name: Date().formattedInTimeZone())
            importFiles = LibraryImport().backupFiles()
        }catch {
            print("ERROR during export")
        }
    }
    
    var body: some View {
        Form {
            Section(header: Text("Backup Library")) {
                Button(action: { self.exportLibrary() }, label: { Text("Do Backup") })
            }
            
            Section(header: Text("Restore Library")) {
                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("Yes, I want to reset my Database", isOn: $backupImportUpdateExistingEntrys)
                Button(action: {
                    LibraryImport().importLIB(from: self.importFiles[self.backupImportFileIndex])
                }, label: { Text("Reset & Import") }).disabled(backupImportFileIndex < 0 || !backupImportUpdateExistingEntrys)
            }
        }.navigationBarTitle("Einstellungen")
    }
}
