//
//  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?
    private let localization: String?
    
    init(delegate: FlutterLogDestinationDelegate? = nil, limitOutputLevel: LogLevel = .debug, localization: String? = nil) {
        self.format = "%Dn [%s|%p]: %m"
        self.limitOutputLevel = limitOutputLevel
        self.localization = localization
        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)" }
        
        if let localization,
           let localeBundlePath = bundle.path(forResource: localization, ofType: "lproj"),
           let localeBundle = Bundle(path: localeBundlePath) {
            let localized = NSLocalizedString(message, bundle: localeBundle, comment: "")
            return String(format: localized, arguments: params)
        } else {
            let localized = NSLocalizedString(message, bundle: bundle, comment: "")
            return String(format: localized, arguments: params)
        }
    }
    
    func process(_ message: String, level: LogLevel) {
        self.delegate?.log(message: message)
    }
}
