//
//  FileButtons.swift
//  SpeedKeys
//
//  Created by Jose Polo Ramos on 2/27/25.
//

import SwiftUI

// FileButtons used to select either the application for launching
// or the file path which the application will launch.
struct FileButtons:View {
    
    @Binding   var data: Entries
    @State     var isApplicationSelected: Bool
    @State     private var showFileImporter: Bool = false
    @State     private var filePath:String
    @Binding   var selected:Entry
    
    init(data: Binding<Entries>, isApplicationSelected: Bool, selected: Binding<Entry>) {
        self._data = data
        self.isApplicationSelected = isApplicationSelected
        self._selected = selected
        self.filePath = isApplicationSelected  ? self._selected.wrappedValue.app : self._selected.wrappedValue.path
    }

    var body: some View {
      
         Button(action: {showFileImporter = true}) {
            Label(filePath.isEmpty ? isApplicationSelected ? "Select Application" : "Select File" : filePath, systemImage: "folder.circle.fill")
                .frame(minWidth: 150)
            
        }.fixedSize(horizontal: false, vertical: true)
                                                  .padding()
                                                  .frame(width: 300, height: 25, alignment: .leading)
                                                  .fileImporter(
                                                    isPresented: $showFileImporter,
                                                    allowedContentTypes: isApplicationSelected ? [.application] : [.folder]
                                                    
                                                  ) { result in
            switch result {
            case .success(let url):
                filePath = url.path                
    
                if(isApplicationSelected){
                    selected.app = url.path

                }else{
                    selected.path = url.path

                }
                showFileImporter = false
            default:
                showFileImporter = false
            }
        }.fileDialogDefaultDirectory(isApplicationSelected  ? .applicationDirectory :  .documentsDirectory  )
            
        
    }
}
