//
//  FileButtonSelector.swift
//  FastCoster
//
//  Created by Michael Pivato on 10/2/2023.
//

import SwiftUI

struct FileButtonSelector: View {
    @State private var showPicker = false
    var label: String
    var onSelected: (String) -> ()
    
    var body: some View {
        Button {
            showPicker.toggle()
        } label: {
            Text(label)
        }.fileImporter(isPresented: $showPicker, allowedContentTypes: [.commaSeparatedText]) { result in
            
            switch result {
            case .success(let fileUrl):
                onSelected(readIntoString(selectedFile: fileUrl))
            case .failure(let error):
                print(error)
            }
        }.padding()
    }
    
    func readIntoString(selectedFile: URL) -> String {
        // https://stackoverflow.com/questions/64118577/getting-the-file-xxx-couldnt-be-opened-because-you-dont-have-permission-to-v
        do {
            if selectedFile.startAccessingSecurityScopedResource() {
                let fileContent = try String(contentsOf: selectedFile)
                defer { selectedFile.stopAccessingSecurityScopedResource() }
                return fileContent
            }
        }catch let error {
            // TODO: Do something about this
            print(error)
        }
        return ""
    }
}

struct FileButtonSelector_Previews: PreviewProvider {
    static var previews: some View {
        FileButtonSelector(label: "Select File"){ response in
            
        }
    }
}
