//
//  Data2View.swift
//  GenjiAPITest
//
//  Created by 森川薫 on 2026/01/14.
//

import SwiftUI

struct Data2View: View {
    @Binding var currentDngNr:Int16
    @State var memsize: Int16=0
    @State var lockMsg: String = ""
    @State var myData: String = ""
    @State var isShowSuccess: Bool = false
    @State var isShowError: Bool = false
    @State var showCannotUnlock: Bool = false
    
    var body: some View {
        
        if currentDngNr > 0{
            
            Spacer()
            
            VStack{
                
                HStack{
                    Text("Memory Size:")
                    
                    Text("\(String(memsize)) bytes")
                        .onAppear {
                            loadData()
                            
                        }
                        .onChange(of: currentDngNr)
                        {
                            loadData()
                        }
                    
                }
                
                HStack{
                    GroupBox{
                        
                        
                        Button("\(lockMsg)"){
                            let ret:Int16
                            if lockMsg == "Data#2 Lock"{
                                ret = Dongle_LockData2(1234, 1, 987654123, currentDngNr, 85)
                                if ret == 1{
                                    lockMsg = "Data#2 Unlock"
                                }
                            }
                            else{
                                ret = Dongle_LockData2(1234, 0, 987654123, currentDngNr, 85)
                                if ret == 1{
                                    lockMsg = "Data#2 Lock"
                                }
                                else{
                                    showCannotUnlock.toggle()
                                }
                            }
                        }
                        .alert("Error", isPresented: $showCannotUnlock) {
                                    // ダイアログ内で行うアクション処理...

                                } message: {
                                    Text("Unable to unlock ( maybe, locked by another program? )")
                                }
                    }
                }
                
                
                TextEditor(text: $myData)
                    .padding([.leading, .trailing], 50)
                    .frame(minHeight: 200)
                
                Button("Write"){
                    let dataLength:Int32 = Int32(myData.lengthOfBytes(using: .utf8))
                    
                    let datalen = withUnsafeBytes(of: dataLength) { Data($0) }
                    
                    let ret = Dongle_WriteData2(1234,[UInt8](datalen)+[UInt8](myData.utf8),0, UInt16(4+dataLength), Int16(currentDngNr), 85)
                    
                    if ret == UInt16(4+dataLength)
                    {
                        isShowSuccess.toggle()
                    }
                    else{
                        isShowError.toggle()
                    }
                }
                .alert("Success", isPresented: $isShowSuccess) {
                    // ダイアログ内で行うアクション処理...
                    
                } message: {
                    Text("Written!")
                }
                .alert("Error", isPresented: $isShowError) {
                    // ダイアログ内で行うアクション処理...
                    
                } message: {
                    Text("Write Error")
                }
            }
            Spacer()
            
        }
    }
    
    func loadData(){
        memsize = Dongle_MemSize2(currentDngNr, 85)
        
        var ret:Int16=0
        
        let ptr = UnsafeMutablePointer<UInt8>.allocate(capacity: 4)
        ret =  Dongle_ReadData2(1234,ptr,0,4,currentDngNr, 85)
        
        if ret == 4
        {
            // UInt8 pointer to UInt32 pointer
            let uint32Pointer = UnsafeRawPointer(ptr)
                .bindMemory(to: UInt32.self, capacity: 1)
            
            let len = UInt32(uint32Pointer.pointee)
            
            if len > 0 && len <= memsize {
                
                let ptr1 = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(len)+1)
                ret = Dongle_ReadData2(1234,ptr1,4,UInt16(len),currentDngNr, 85)
                
                if ret == UInt16(len)
                {
                    myData = String(cString: ptr1)
                }
                
                ptr1.deallocate()
            }
        }
        ptr.deallocate()
        
       
        // can lock?
        ret = Dongle_LockData2(1234, 1, 987654123, currentDngNr, 85)

        // yes, meaning genji is not locked
        if ret == 1
        {
            // unlock
            ret = Dongle_LockData2(1234, 0, 987654123, currentDngNr, 85)
            
            lockMsg = "Data#2 Lock"
        }
        // already locked
        else if ret == -9
        {
            lockMsg = "Data#2 Unlock"
        }
        
    }
}

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