//
//  GMNetMonitorUtils.swift
//  AFNetworking
//
//  Created by Jing on 2019/5/28.
//

import Foundation
import Alamofire
import CommonCrypto

public class GMNetMonitorUtils: NSObject {
    // 需要监控的域名
    static var monitorDomains : [String]?
}

public extension GMNetMonitorUtils {
    @objc(needMonitorDomainsWithDomains:)
     public static func needMonitorDomains(_ domains: [String]) {
        GMNetMonitorUtils.monitorDomains = domains
    }
}

public extension GMNetMonitorUtils {
//    @objc(sendNetMonitorDataWithResponse:traceId:)
    public static func sendNetMonitorData(_ response: DataResponse<Any>?, _ traceId: String) -> Dictionary<String, String>? {
        
        if #available(iOS 10.0, *) {
            guard
                let metrics = response?.metrics,
                let host = response?.request?.url?.host,
                let containsHost = GMNetMonitorUtils.monitorDomains?.contains(host)
                else {
                    return nil
            }
            
            var trackData = [String: String]()
            for transactionMetrics in metrics.transactionMetrics {
                trackData["data_type"] = "1"
                trackData["trace_id"] = traceId
                trackData["task_start_time"] = self.timeString(date: transactionMetrics.fetchStartDate)
                trackData["dns_start_time"] = self.timeString(date: transactionMetrics.domainLookupStartDate)
                trackData["dns_end_time"] = self.timeString(date: transactionMetrics.domainLookupEndDate)
                trackData["connect_start_time"] = self.timeString(date: transactionMetrics.connectStartDate)
                trackData["secure_start_time"] = self.timeString(date: transactionMetrics.secureConnectionStartDate)
                trackData["secure_end_time"] = self.timeString(date: transactionMetrics.secureConnectionEndDate)
                trackData["connect_end_time"] = self.timeString(date: transactionMetrics.connectEndDate)
                trackData["request_start_time"] = self.timeString(date: transactionMetrics.requestStartDate)
                trackData["request_end_time"] = self.timeString(date: transactionMetrics.requestEndDate)
                trackData["response_start_time"] = self.timeString(date: transactionMetrics.responseStartDate)
                trackData["response_end_time"] = self.timeString(date: transactionMetrics.responseEndDate)
                trackData["task_end_time"] = self.timeString(date: metrics.taskInterval.end)
                
                if let bodyCount = response?.request?.httpBody?.count {
                    trackData["request_data_size"] = String.init(format: "%ld", bodyCount)
                } else {
                    trackData["request_data_size"] = ""
                }
                if let length = response?.response?.expectedContentLength{
                    trackData["response_data_size"] = String.init(format: "%ld", length)
                } else {
                    trackData["response_data_size"] = ""
                }
                return trackData
            }
        }
        return nil
    }
    
    static func timeString(date: Date?) -> String {
        guard date != nil else {
            return ""
        }
        let time = date!.timeIntervalSince1970;
        return String.init(format: "%lld", time * 1000000000)
    }
}

public extension GMNetMonitorUtils {
    @objc(createTraceId)
    public static func createTraceId() -> String {
        var traceId = ""
        // 1、先取 当前时间 按照 "年/月/日/时分" 转换 作为traceId的上半部分--> 2018/10/25/1821
        let date = NSDate.init(timeIntervalSinceNow: 0)//获取当前时间0秒后的时间
        let timeNow = date.timeIntervalSince1970
        
        traceId = traceId.appendingFormat("%@", getDateStringWithTimeStr(timeNow))
        
        // 2、取当前的时间戳 + 随机字符串(长度 32) 组成字符串，将该字符串 MD5哈希，取该哈希值的前 12位 作为图片路径的下半部分 --> caf8f8d86886
        let timeNowStr = NSString.init(format: "%ld", timeNow)
        let secondPart = timeNowStr.appendingFormat("%@", getRadomString())
        
        let secondPartMD5 = MD5ForLower32Bate(secondPart as String)
        
        return NSString.init(format: "%@/%@", traceId, (secondPartMD5 as NSString).substring(to: 12)) as String
    }
    static func getDateStringWithTimeStr(_ time: TimeInterval) -> String {
        let detailDate = NSDate.init(timeIntervalSince1970: time)
        let dateFormatter = DateFormatter.init() //实例化一个NSDateFormatter对象
        //设定时间格式,这里可以设置成自己需要的格式
        dateFormatter.dateFormat = "yyyy/MM/dd/HHmm"
        return dateFormatter.string(from: detailDate as Date);
    }
    
    static func getRadomString() -> String {
        let array = NSArray.init(objects: "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9")
        let randomArray = NSMutableArray.init()
        while randomArray.count < 32 {
            let random = Int(arc4random())
            let r = random % array.count
            randomArray.add(array.object(at: r))
        }
        
        return randomArray.componentsJoined(by: "")
    }
    
    static func MD5ForLower32Bate(_ str: String) -> String {
        //要进行UTF8的转码
        let input = str.cString(using: String.Encoding.utf8)
        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 16)
        CC_MD5(input, CC_LONG(strlen(input!)), buffer)
        var md5String = ""
        for idx in 0...15 {
            let obcStrl = String.init(format: "%02x", buffer[idx]);
            md5String.append(obcStrl);
        }
        free(buffer);
        return md5String;
    }
}
