//
/*
 * Copyright (c) 2021 BWI GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import Foundation
import WebKit

@objcMembers class UserAgentService : NSObject {
 
    private func networkVersion() -> String? {
        guard let bundle = Bundle(identifier: "com.apple.CFNetwork"),
              let versionAny = bundle.infoDictionary?[kCFBundleVersionKey as String],
              let version = versionAny as? String else {
                  return nil
                  
              }
           return version
    }
    
    private func darwinVersion() -> String? {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.release)
        let darwinVersion = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8,
              value != 0 else {
                return identifier
            }

            return identifier + String(UnicodeScalar(UInt8(value)))
        }
        
        return darwinVersion
    }
    
    private func deviceName() -> String {

            var systemInfo = utsname()
            uname(&systemInfo)

            let machineMirror = Mirror(reflecting: systemInfo.machine)
            let identifier = machineMirror.children.reduce("") { identifier, element in
                guard let value = element.value as? Int8, value != 0 else { return identifier }
                return identifier + String(UnicodeScalar(UInt8(value)))
            }

            return identifier
        }
    
    var bwiUserAgentDict: [String : String] {
        return ["User-Agent" : bwiUserAgent]
    }
    
    var bwiUserAgent: String {
        
        var flavor = BWIBuildSettings.shared.flavor
        
        if (ServerURLHelper.shared.flavor() != nil) {
            flavor = ServerURLHelper.shared.flavor()!
        }
        
        let appName: String
        if !BWIBuildSettings.shared.secondaryAppName.isEmpty {
            appName = BWIBuildSettings.shared.secondaryAppName
        } else {
            appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as! String
        }

        guard let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString"),
                let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion"),
                let network = self.networkVersion(),
                let darwin = self.darwinVersion()
        else {
            return flavor
        }

        let model = UIDevice.current.model
        let platform = UIDevice.current.systemName
        let operationSystemVersion = ProcessInfo.processInfo.operatingSystemVersionString
        let deviceName = self.deviceName()
        
        let agent = "\(appName)/\(version) (\(build); \(model); \(platform); \(deviceName); \(operationSystemVersion); \(flavor); \(network)/\(darwin);)"
         
        return agent
    }
}
