//
//  HMGPlatformBridge.swift
//  Runner
//
//  Created by ZiKambrani on 14/12/2020.
//

import UIKit
import NetworkExtension
import SystemConfiguration.CaptiveNetwork

var flutterMethodChannel:FlutterMethodChannel? = nil
fileprivate var mainViewController:MainFlutterVC!

class HMGPlatformBridge{
    private let channelName = "HMG-Platform-Bridge"
    private static var shared_:HMGPlatformBridge?
    
    class func initialize(flutterViewController:MainFlutterVC){
        shared_ = HMGPlatformBridge()
        mainViewController = flutterViewController
        shared_?.openChannel()
    }
    
    func shared() -> HMGPlatformBridge{
        assert((HMGPlatformBridge.shared_ != nil), "HMGPlatformBridge is not initialized, call initialize(mainViewController:MainFlutterVC) function first.")
        return HMGPlatformBridge.shared_!
    }
    
    private func openChannel(){
        flutterMethodChannel = FlutterMethodChannel(name: channelName, binaryMessenger: mainViewController.binaryMessenger)
        flutterMethodChannel?.setMethodCallHandler { (methodCall, result) in
            print("Called function \(methodCall.method)")
            if methodCall.method == "connectHMGInternetWifi"{
                self.connectHMGInternetWifi(methodCall:methodCall, result: result)
                
            }else if methodCall.method == "connectHMGGuestWifi"{
                self.connectHMGGuestWifi(methodCall:methodCall, result: result)
                
            }else if methodCall.method == "isHMGNetworkAvailable"{
                self.isHMGNetworkAvailable(methodCall:methodCall, result: result)
                
            }else if methodCall.method == "registerHmgGeofences"{
                self.registerHmgGeofences(result: result)
                
            }else if methodCall.method == "unRegisterHmgGeofences"{
                self.unRegisterHmgGeofences(result: result)
            }
            
            print("")
        }
        Timer.scheduledTimer(withTimeInterval: 0.1, repeats: false) { (timer) in
            FlutterConstants.set()
        }
    }
    
    
    
    // Connect HMG Wifi and Internet
    func connectHMGInternetWifi(methodCall:FlutterMethodCall ,result: @escaping FlutterResult){
        
        guard let pateintId = (methodCall.arguments as? [Any])?.first as? String
            else { return assert(true, "Missing or invalid arguments (Must have one argument 'String at 0'") }
        
        
        HMG_Internet.shared.connect(patientId: pateintId) { (status, message) in
            result(status ? 1 : 0)
            if status{
                self.showMessage(title:"Congratulations", message:message)
            }else{
                self.showMessage(title:"Ooops,", message:message)
            }
        }
    }
    
    // Connect HMG-Guest for App Access
    func connectHMGGuestWifi(methodCall:FlutterMethodCall ,result: @escaping FlutterResult){
        HMG_GUEST.shared.connect() { (status, message) in
            result(status ? 1 : 0)
            if status{
                self.showMessage(title:"Congratulations", message:message)
            }else{
                self.showMessage(title:"Ooops,", message:message)
            }
        }
    }
    
    func isHMGNetworkAvailable(methodCall:FlutterMethodCall ,result: @escaping FlutterResult) -> Bool{
        guard let ssid = methodCall.arguments as? String else {
            assert(true, "Missing or invalid arguments (Must have one argument 'String at 0'")
            return false
        }
        
        let queue = DispatchQueue.init(label: "com.hmg.wifilist")
        NEHotspotHelper.register(options: nil, queue: queue) { (command) in
            print(command)
            
            if(command.commandType == NEHotspotHelperCommandType.filterScanList) {
                if let networkList = command.networkList{
                    for network in networkList{
                        print(network.ssid)
                    }
                }
            }
        }
        return false
        
    }
    
    
    // Message Dailog
    func showMessage(title:String, message:String){
        DispatchQueue.main.async {
            let alert = UIAlertController(title: title, message: message, preferredStyle: .alert )
            alert.addAction(UIAlertAction(title: "OK", style: .destructive, handler: nil))
            mainViewController.present(alert, animated: true) {
                
            }
        }
    }
    
    // Register Geofence
    func registerHmgGeofences(result: @escaping FlutterResult){
        flutterMethodChannel?.invokeMethod("getGeoZones", arguments: nil){ geoFencesJsonString in
            if let jsonString = geoFencesJsonString as? String{
                let allZones = GeoZoneModel.list(from: jsonString)
                HMG_Geofence.shared().register(geoZones: allZones)
                result(true)
            }else{
            }
        }
    }
    
    // Register Geofence
    func unRegisterHmgGeofences(result: @escaping FlutterResult){
        HMG_Geofence.shared().unRegisterAll()
        result(true)
    }

}
