//
//  CallBackFunctionView.swift
//  SIIMpaPrinterSample
//

import SwiftUI

struct CallBackFunctionView: View {
    @ObservedObject var printerViewModel: PrinterViewModel
    @StateObject var statusViewModel: StatusViewModel = StatusViewModel()
    @State private var isStartCallbackSuccess: Bool = false
    @Environment(\.dismiss) var dismiss
    var body: some View {
        VStack {
            List {
                Section(statusViewModel.online.title) {
                    Text(statusViewModel.online.status.rawValue)
                        .foregroundColor(statusViewModel.online.status.color)
                }
                Section(CALLBACK_STATUS_SECTION) {
                    ForEach(statusViewModel.statusTable, id: \.self) { statusItem in
                        HStack {
                            Text(statusItem.title)
                            Spacer()
                            Text(statusItem.status.rawValue)// get status
                                .foregroundColor(statusItem.status.color)
                        }
                    }
                }
            }
            .listStyle(.plain)
        }
        .navigationTitle("Callback function")
        .onAppear() {
            PrinterManager.getDispatchQueue().async {
                printerViewModel.showIndicator(true)
                isStartCallbackSuccess = PrinterManager.startCallBack(status: statusViewModel, sel: #selector(StatusViewModel.statusChanged(status:)))
                if isStartCallbackSuccess == false {
                    printerViewModel.setAlert(PrinterManager.getResultString())
                    DispatchQueue.main.async {
                        dismiss()
                    }
                }
                printerViewModel.showIndicator(false)
            }
        }
        .onDisappear() {
            if isStartCallbackSuccess == true {
                PrinterManager.stopCallBack()
            }
        }
    }
}
