//
//  Logger.swift
//  Poker Analytics 4
//
//  Created by Laurent Morvillier on 29/03/2018.
//

import Foundation

@objc public class Logger : NSObject {
    
    @objc static public func log(_ message: Any, file: String = #file, function: String = #function, line: Int = #line) {
        let filestr: NSString = NSString(string: file)
        print("\(filestr.lastPathComponent).\(line).\(function): \(message)")
    }
    
    @objc static public func error(_ error: Error) {
        Logger.error(error, file: #file, function: #function, line: #line)
    }
    
    static public func error(_ error: Error, file: String = #file, function: String = #function, line: Int = #line) {
        let filestr: NSString = NSString(string: file)
        var fireBaseError: Error {
            if let customError = error as? CustomNSError & LocalizedError {
                return customError.fireBaseError
            } else {
                return error
            }
        }
        print("ERROR: \(filestr.lastPathComponent).\(line).\(function): \(fireBaseError)")
    }
    
    @objc static public func w(_ message: Any, file: String = #file, function: String = #function, line: Int = #line) {
        let filestr: NSString = NSString(string: file)
        print("Warning: \(filestr.lastPathComponent).\(line).\(function): \(message)")
    }
        
    @objc static public func crashLogging(_ message: String, file: String = #file, function: String = #function, line: Int = #line) {
        let fileName: String = file.components(separatedBy: "/").last ?? file
        #if DEBUG
        NSLogv("%@.%i.%@: %@", getVaList([fileName, line, function, message]))
        #else
        NSLogv("%@.%i.%@: %@", getVaList([fileName, line, function, message]))
        #endif
    }
    
}

extension LocalizedError where Self: CustomNSError {
    var simpleErrorDescription: String {
        let mirror = Mirror(reflecting: self)
        if let label = mirror.children.first?.label {
            return label
        } else {
            return String(describing:self)
        }
    }
    
    var fireBaseError: NSError {
        NSError(domain: Self.errorDomain + "." + self.simpleErrorDescription, code: self.errorCode, userInfo: self.errorUserInfo)
    }
}
