//
//  YHConfigManager.swift
//  galaxy
//
//  Created by davidhuangA on 2024/4/11.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHConfigManager: NSObject {
    static let shared = YHConfigManager()
    
    lazy var reqVM: YHHomePageViewModel = {
        let vm = YHHomePageViewModel()
        return vm
    }()
    
    private(set) var loadNewDataFlag : Bool = false
    
    private override init() {
        super.init()
    }
    
    
    //测试环境-H5
    static let baseH5UrlTest : String = "https://test-hkdiy-h5.galaxy-immi.com"
    //正式环境-H5
    static let baseH5UrlRelease : String = "https://hkdiy-h5.galaxy-immi.com"
    
    //h5地址
    var h5Url : String {
        var tH5url = reqVM.configModel?.article_h5_url ?? ""
        if tH5url.isEmpty {
#if DEBUG
            tH5url = YHConfigManager.baseH5UrlTest
#elseif TESTENV
            tH5url = YHConfigManager.baseH5UrlTest
#elseif UATENV
            tH5url = YHConfigManager.baseH5UrlRelease
#else
            tH5url = YHConfigManager.baseH5UrlRelease
#endif
        }
        
        if !loadNewDataFlag {
            loadConfigData()
        }
        return tH5url + "/"
    }
    
    //测试环境-OSS
    static let baseOSSUrlTest : String = "https://test-comserver.galaxy-immi.com"
    //正式环境-OSS
    static let baseOSSUrlRelease : String = "https://comserver.galaxy-immi.com"
    
    //OSS
    var ossUrl : String {
        var tOssUrl = reqVM.configModel?.oss_server ?? ""
        if tOssUrl.isEmpty {
#if DEBUG
            tOssUrl = YHConfigManager.baseOSSUrlTest
#elseif TESTENV
            tOssUrl = YHConfigManager.baseOSSUrlTest
#elseif UATENV
            tOssUrl = YHConfigManager.baseOSSUrlRelease
#else
            tOssUrl = YHConfigManager.baseOSSUrlRelease
#endif
        }
        
        if !loadNewDataFlag {
            loadConfigData()
        }
        return tOssUrl + "/"
    }
}

extension YHConfigManager {
    func loadConfigData(_ callback:(()->())? = nil) {
        
        if YHNetworkStatusManager.shared.isNetWorkOK == false {
            callback?()
            return
        }
        
        DispatchQueue.global().async {
            self.reqVM.getHomeConfig { flag, error in
                DispatchQueue.main.async {
                    if flag {
                        self.loadNewDataFlag = true
                        callback?()
                    }
                }
            }
        }
    }
}
