//
//  SpeakAlertHUD.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/18.
//

import UIKit

class SpeakAlertHUD: NSObject {

    static let share = SpeakAlertHUD()
    
    private lazy var loadingView:SpeakLoadingView = {
        let loadingView = SpeakLoadingView()
        loadingView.frame = CGRect(x: 0, y: 0, width: Dev.screenW, height: Dev.screenH)
        return loadingView
    }()
    
    func config(){
        loadingView.isHidden = false
    }
    
    func show(){
        disMiss()
        DispatchQueue.main.async {
            SpWindow.addSubview(self.loadingView)
            SpWindow.bringSubviewToFront(self.loadingView)
            self.loadingView.activity.startAnimating()
        }
    }
    
    func show(_ afterClose:TimeInterval? = 1.5){
        disMiss()
        DispatchQueue.main.async {
            SpWindow.addSubview(self.loadingView)
            SpWindow.bringSubviewToFront(self.loadingView)
           self.loadingView.activity.startAnimating()
        }
        if afterClose ?? 0 > 0 {
            DispatchQueue.main.asyncAfter(deadline: .now() + (afterClose ?? 1)) {
                self.disMiss()
            }
        }
    }
    
    
    func disMiss(){
        DispatchQueue.main.async {
            self.loadingView.activity.stopAnimating()
            self.loadingView.removeFromSuperview()
        }
    }
    
    func setTimerDismiss(){
        
    }
}

fileprivate class SpeakLoadingView: UIView {
    
    var contentV:UIView!
    var activity:UIActivityIndicatorView!
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        self.backgroundColor = UIColor.black.withAlphaComponent(0)
        contentV = UIView()
        contentV.backgroundColor = .init(hex: 0x444444)
        contentV.corners = 12
        addSubview(contentV)
        // 设置约束
        
        activity = UIActivityIndicatorView(style: .large)
        activity.color = .white
        contentV.addSubview(activity)
        
        setupConstraints()
    }
    
    private func setupConstraints() {

        contentV.snp.makeConstraints { make in
            make.centerX.centerY.equalToSuperview()
            make.size.equalTo(CGSizeMake(100,100))
        }
        activity.snp.makeConstraints { make in
            make.centerX.centerY.equalToSuperview()
        }
    }

}
