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

import SwiftUI

struct OverheadAllocation: View {
    // TODO: Refactor to take inputs from another task instead
    @State private var lines: String?
    @State private var accounts: String?
    @State private var areas: String?
    @State private var allocationStatistics: String?
    @State private var costCentres: String?
    @State private var showMovePicker = false
    @State private var accountType = "E"
    @State private var showFrom = false
    @State private var tempPath: URL?;
    
    var body: some View {
        VStack {
            FileButtonSelector(label: "Select Lines File") {result in
                lines = result
            }
            FileButtonSelector(label: "Select Accounts File") {result in
                accounts = result
            }
            FileButtonSelector(label: "Select Areas File") {result in
                areas = result
            }
            FileButtonSelector(label: "Select Allocation Statistics File") {result in
                allocationStatistics = result
            }
            FileButtonSelector(label: "Select Cost Centres File") {result in
                costCentres = result
            }
            TextField("Account Type", text: $accountType)
            Toggle(isOn: $showFrom) {
                Text("Show from cc movements")
            }
            Button {
                allocate_overheads()
            } label: {
                Text("Allocate Overheads")
            }.padding()
                .fileMover(isPresented: $showMovePicker, file: tempPath) { result in
                    if case .success = result {
                        do {
                            try FileManager.default.removeItem(at: tempPath!)
                        } catch {
                            
                        }
                    }else {
                        print(result)
                    }
                }
        }.padding()
            .textFieldStyle(.roundedBorder)
    }
    
    func allocate_overheads() {
        tempPath = FileManager.default.temporaryDirectory.appendingPathComponent("OverheadAllocation.csv", conformingTo: .commaSeparatedText)
        // Cut off file://
        // TODO: There has to be a better way to do string slicing right?
        let tempPathString = String(tempPath!.absoluteString.dropFirst(7))
        DispatchQueue.global(qos: .userInitiated).async {
            allocate_overheads_from_text_to_file(lines, accounts, allocationStatistics, areas, costCentres, accountType, tempPathString, false, showFrom)
            
            DispatchQueue.main.async {
                showMovePicker = true;
            }
        }
    }
}

struct OverheadAllocation_Previews: PreviewProvider {
    static var previews: some View {
        OverheadAllocation()
    }
}
