//
//  NetworkController.swift
//  iPOS
//
//  Created by BBC on 06/10/16.
//  Copyright © 2016 BBC. All rights reserved.
//

import Foundation
import UIKit
import SystemConfiguration

public class NetworkController {
    
    static func isConnectedToNetwork() -> Bool {
        
        var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
        zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)
        
        let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
                SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
            }
        }
        
        var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
        if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
            return false
        }
        
        let isReachable = flags == .reachable
        let needsConnection = flags == .connectionRequired
        
        return isReachable && !needsConnection
        
    }
    
    static func AlertConnectionError(viewController: UIViewController){
        let title: String = Util.getString("No network connection!")
        let message: String = Util.getString("Check your internet settings and try again")
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let Ok = UIAlertAction(title: "Ok", style: .default)
        alertController.addAction(Ok)
        viewController.present(alertController, animated: true, completion: nil)
    }
}
