//
//  CopyCrashHandler.swift
//  SwiftProject
//
//  Created by aaa on 2024/3/20.
//

import Foundation
//public class CopyCrashHandler
//{
//    public static func setup(callBack:@escaping CrashCallback){
//        crashCallBack = callBack;
//        registerSignalHanlder();
//    }
//}
//
//public typealias Completion = ()->Void;
//public typealias CrashCallback = (String,Completion)->Void;
// 
//public var crashCallBack: CrashCallback?
//
//
//
//
//func signalHandler(signal:Int32) -> Void {
//    let stackTrace = Thread.callStackSymbols.joined(separator: "\r\n")
//    crashCallBack?(stackTrace,{
//        unregisterSignalHandler();
//        exit(signal);
//    });
//}
// 
//func registerSignalHanlder()
//{
//    objc_setUncaughtExceptionHandler { (_response:Any?) in
//        if let signal = _response as? Int32 {
//            signalHandler(signal: signal)
//        }
//        else if let exception = _response as? NSException {
//            crashCallBack?(exception.reason ?? exception.callStackSymbols.joined(separator: "\r\n"),{
//                unregisterSignalHandler();
//                exception.raise()
//            });
//        }
//    }
//    
//    signal(SIGINT,  signalHandler);
//    signal(SIGSEGV, signalHandler);//野指针，僵尸对象
//    signal(SIGTRAP, signalHandler);
//    signal(SIGABRT, signalHandler);
//    signal(SIGILL,  signalHandler);
//    signal(SIGBUS,  signalHandler);
//    signal(SIGFPE,  signalHandler);
//    signal(SIGTERM, signalHandler);
//    signal(SIGKILL, signalHandler);//CPU无法执行的代码(比如无效指令、除以0等)
//    signal(SIGPIPE, signalHandler);
//}
// 
//func unregisterSignalHandler()
//{
//    signal(SIGINT,  SIG_DFL);
//    signal(SIGSEGV, SIG_DFL);
//    signal(SIGTRAP, SIG_DFL);
//    signal(SIGABRT, SIG_DFL);
//    signal(SIGILL,  SIG_DFL);
//    signal(SIGBUS,  SIG_DFL);
//    signal(SIGFPE,  SIG_DFL);
//    signal(SIGTERM, SIG_DFL);
//    signal(SIGKILL, SIG_DFL);
//    signal(SIGPIPE, SIG_DFL);
//}
// 
//

public class CopyCrashHandler {
    public class func getdataPath() -> String{
            let str = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!
            let urlPath = str.appending("Exception.txt")
            return urlPath
        }
    public class func setDefaultHandler() {
            NSSetUncaughtExceptionHandler { (exception) in
                let arr:NSArray = exception.callStackSymbols as NSArray
                let reason:String = exception.reason!
                let name:String = exception.name.rawValue
                let date:NSDate = NSDate()
                let timeFormatter = DateFormatter()
                timeFormatter.dateFormat = "YYYY/MM/dd hh:mm:ss SS"
                let strNowTime = timeFormatter.string(from: date as Date) as String
                let url:String = String.init(format: "time:%@\nname:%@\nreason:\n%@\ncallStackSymbols:\n%@",strNowTime,name,reason,arr.componentsJoined(by: "\n"))
                let path = CopyCrashHandler.getdataPath()
                do{
                    if FileManager.default.fileExists(atPath: path) {
                        try FileManager.default.removeItem(atPath: path)
                    }
                    
                    try url.write(toFile: path, atomically: true, encoding: String.Encoding.utf8)
                }catch{ error
                    print("\(error)")
                }
            }
      }

}
