//
//  FlutterLogDestination.swift
//  nut_player_ios
//
//  Created by Juraldinio on 10/2/23.
//

import Foundation
import NutPlayer

protocol FlutterLogDestinationDelegate: AnyObject {
    func log(message: String)
}

final class FlutterLogDestination: LogDestination {
    
    let format: String
    let limitOutputLevel: LogLevel
    private weak var delegate: FlutterLogDestinationDelegate?
    
    private let bundle: Bundle?
    
    init(delegate: FlutterLogDestinationDelegate? = nil, limitOutputLevel: LogLevel = .debug) {
        self.format = "%Dn [%s|%p]: %m"
        self.limitOutputLevel = limitOutputLevel
        self.delegate = delegate
        
        if let bundleUrl = Bundle(for: Self.self).url(forResource: "nut_player_ios", withExtension: "bundle") {
            self.bundle = Bundle(url: bundleUrl)
        } else {
            self.bundle = nil
        }
    }
    
    func localize(_ message: String, params: [String]) -> String {
        guard let bundle else { return "\(message) \(params)" }
        
        let localized = NSLocalizedString(message, bundle: bundle, comment: "")
        return String(format: localized, arguments: params)
    }
    
    func process(_ message: String, level: LogLevel) {
        self.delegate?.log(message: message)
    }
}
