//
//  GMFGRouterWifiHandler.swift
//  MVM5G
//
//  Created by Rajesh on 12/9/20.
//  Copyright © 2020 Kyle. All rights reserved.
//
import Foundation
import CoreBluetooth

protocol GMFGRouterWifiDelegate: AnyObject {
    func routerWifi(credentials: GMFGRouterWifiInfo)
    func routerWifiStatus(status: GMFGRouterWifiStatus)
}

struct GMFGRouterWifiInfo {
    var ssid: String
    var password: String
}

enum GMFGRouterWifiStatus: String {
    case disabled = "Disabled"
    case notReady = "NotReady"
}

class GMFGRouterWifiHandler: GMFGBLEHandlerProtocol {
    
    private let multicast = MulticastDelegate<GMFGRouterWifiDelegate>()

    public func setDelegate(delegates: [GMFGRouterWifiDelegate?]) {
        self.multicast.add(delegates: delegates)
    }
    
    public func reset() {
        self.multicast.removeAll()
    }
    
    public func fetchRouterWifiCredentials(_ peripheral: CBPeripheral, _ characteristic: CBCharacteristic) {
       peripheral.readValue(for: characteristic)
    }
    
    public func response(response: [String : Any]) {
        guard let wifiSSID = response["SSID"] as? String, let wifiPwd = response["Password"] as? String else { return }
        multicast.invokeForEachDelegate{ $0.routerWifi(credentials: GMFGRouterWifiInfo.init(ssid: wifiSSID, password: wifiPwd)) }
        reset()
    }
    
    public func deviceNotReady() {
        multicast.invokeForEachDelegate{ $0.routerWifiStatus(status: .notReady) }
    }
}
