//
//  BleScanTool.swift
//  PrinterDemo
//
//  Created by ldc on 2025/8/29.
//  Copyright © 2025 XiamenHY. All rights reserved.
//

import Foundation
import PrinterSDK
import RYCommunication

protocol BleScanner {
    
    func start(discoverListener: @escaping ([BleTarget]) -> Void) -> Void
    
    func stop() -> Void
}

class BKCentralManagerBleScanner: BleScanner {
    
    var iden: String?
    
    var targets: [BleTarget] = []
    
    func start(discoverListener: @escaping ([BleTarget]) -> Void) {
        self.targets = []
        discoverListener(self.targets)
        self.iden = RYCentralManager.share().startScan(-1) { [weak self] (accessory) in
            if let _ = self?.targets.firstIndex(where: { temp in
                return temp.btName == accessory.btName
            }) {
//                self?.targets[index] = accessory
//                discoverListener(self?.targets ?? [])
            }else {
                self?.targets.append(accessory)
                discoverListener(self?.targets ?? [])
            }
        } powerOffBlock: { [weak self] in
            print("power off")
            self?.iden = nil
            self?.targets = []
            discoverListener(self?.targets ?? [])
        } scanTimeoutBlock: { [weak self] in
            print("timeout")
            self?.iden = nil
        } printerFilter: { peripheral, _, _ in
            guard let name = peripheral.name else { return false }
            return !name.isEmpty
        }
    }
    
    func stop() {
        if let iden = self.iden {
            self.iden = nil
            RYCentralManager.share().stopScan(iden)
        }
    }
}

class BleScannerFactory {
    static func generate() -> BleScanner {
        return BKCentralManagerBleScanner()
    }
}
