//
//  DongleListView.swift
//  GenjiAPITest
//
//

import SwiftUI


struct Dongle: Identifiable {
    let id = UUID()
    let gusn: String
    let dngNr: Int16
}

struct DongleListView: View {
    @State var dongles: [Dongle] = []
    @State var selectedDngNr: Int16 = 0
    @Binding var currentDngNr: Int16
    
    var body: some View {
        List(selection: $selectedDngNr) {
            ForEach(dongles){ dongle in
                Text(dongle.gusn).tag(dongle.dngNr)
            }
        }
        .onReceive(NotificationCenter.default.publisher(for: Notification.Name("DonglesChanged"))) { _ in
                    fillList()
         }
        .onAppear {
            fillList()
        }
        .onChange(of: selectedDngNr) { listItemChanged()}
        
        

    }
    
    func listItemChanged()
    {
        currentDngNr = selectedDngNr

    }
    
    func fillList(){
               
      
        Task {
            
           //await startSleepTimer(seconds: 2)
            try? await Task.sleep(nanoseconds: 1_500_000_000)
           
            dongles.removeAll()

            Init_MatrixAPI()
            let count:Int16 = Dongle_Count(85)
            
            if count > 0
            {
                for i in 0..<Int(count)
                {                   
                    let ptr = UnsafeMutablePointer<UInt8>.allocate(capacity: 24)
                    
                    var sn:String=""
                    
                    let dngNr:Int16=Int16(i+1)
                    
                    if Dongle_ReadGUSN(1234,ptr,dngNr,85) == 1{
                        sn = String(format:"%s",ptr)
                    }
                    else{
                        dongles.removeAll()
                        return
                    }
                            
                    dongles.append(Dongle(gusn: sn, dngNr: dngNr))
                   
                    ptr.deallocate();

                }
                
                selectedDngNr = 1
            }
            else{
                selectedDngNr = 0
            }
                
            Release_MatrixAPI()
        }
    }
}

#Preview {
    @Previewable @State var dngNr:Int16=0
    DongleListView(currentDngNr:$dngNr)
}
