//
//  LanguageManager.swift
//  vectorsearch
//
//  Created by Du Qingjie on 2024/08/31.
//

import SwiftUI

class LanguageManager: ObservableObject {
    @Published var currentLanguage: String = Locale.current.language.languageCode?.identifier ?? "en" {
        didSet {
            updateLocalization()
        }
    }

    func updateLocalization() {
        Bundle.setLanguage(currentLanguage)
        // Trigger UI update by changing @Published property
        objectWillChange.send()
    }
}

extension Bundle {
    private static var bundleKey: UInt8 = 0

    static func setLanguage(_ language: String) {
        defer {
            object_setClass(Bundle.main, BundleEx.self)
        }
        objc_setAssociatedObject(Bundle.main, &bundleKey, language, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }

    var localizedBundle: Bundle? {
        guard let language = objc_getAssociatedObject(self, &Bundle.bundleKey) as? String else {
            return nil
        }
        return Bundle(path: Bundle.main.path(forResource: language, ofType: "lproj")!)
    }
}

private class BundleEx: Bundle {
    override func localizedString(forKey key: String, value: String?, table tableName: String?) -> String {
        return localizedBundle?.localizedString(forKey: key, value: value, table: tableName) ?? super.localizedString(forKey: key, value: value, table: tableName)
    }
}
