//
//  String+TUILocalized.swift
//  Lanu
//
//  Created by OneeChan on 2025/12/18.
//

import Foundation


class TIMLocalizedText {
    static let shared = TIMLocalizedText()
    private var commonBundle: Bundle?
    private var faceBundle: Bundle?
    
    private init() {
        rebuildBundle()
        LNEventDeliver.addObserver(self)
    }
    
    func commonText(_ key: String) -> String {
        commonBundle?.localizedString(forKey: key, value: key, table: nil) ?? key
    }
    
    func faceText(_ key: String) -> String {
        faceBundle?.localizedString(forKey: key, value: key, table: nil) ?? key
    }
}

extension TIMLocalizedText: LNAppMainEvent {
    func onAppLanguageChanged(newLanguage: LNAppLanguage) {
        rebuildBundle()
    }
}

extension TIMLocalizedText {
    private func rebuildBundle() {
        let curLan = LNAppConfig.shared.curLang.bundleName
        var language = "Localizable/" + curLan
        
        let commonPath = Bundle(path: Bundle.main.path(forResource: "TIMCommonLocalizable", ofType: "bundle")!)!
        if commonPath.path(forResource: language, ofType: "lproj") == nil {
            language = "Localizable/" + LNAppLanguage.english.bundleName
        }
        commonBundle = Bundle(path: commonPath.path(forResource: language, ofType: "lproj")!)
        
        let facePath = Bundle(path: Bundle.main.path(forResource: "TUIChatFace", ofType: "bundle")!)!
        faceBundle = Bundle(path: facePath.path(forResource: language, ofType: "lproj")!)
    }
}
