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

import SwiftUI

struct MoveMoney: View {
    
    @State private var showExportPicker = false
    @State private var document: CsvDocument?
    @State private var lines: String?
    @State private var rules: String?
    @State private var costCentres: String?
    @State private var accounts: String?
    var body: some View {
        VStack {
            FileButtonSelector(label: "Select Rules File") { result in
                rules = result
            }
            FileButtonSelector(label: "Select Lines File") { result in
                lines = result
            }
            FileButtonSelector(label: "Select Cost Centres File") { result in
                costCentres = result
            }
            FileButtonSelector(label: "Select Accounts File") { result in
                accounts = result
            }
            Button {
                move_money()
            } label: {
                Text("Move money")
            }.padding()
                .fileExporter(isPresented: $showExportPicker, document: document, contentType: .commaSeparatedText) { result in
                    
                    if case .success = result {
                        
                    }else {
                        
                    }
                    
                }
        }
        .padding()
        
    }
    
    func move_money() {
        DispatchQueue.global(qos: .userInitiated).async {
            // Run move money
            let result = move_money_from_text(rules, lines, accounts, costCentres, false)
            
            DispatchQueue.main.async {
                document = CsvDocument(data: String(cString: result!))
                move_money_from_text_free(result)
                showExportPicker = true;
            }
        }
    }
}

struct MoveMoney_Previews: PreviewProvider {
    static var previews: some View {
        MoveMoney()
    }
}
