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

import Foundation

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 cleanCrashInfo() {
        let path = CopyCrashHandler.getdataPath()
        do{
            if FileManager.default.fileExists(atPath: path) {
                try FileManager.default.removeItem(atPath: path)
            }
        }catch{
        }
    }
    
    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{ 
                }
            }
      }

}
