//
//  LoadingAlert.swift
//  WeiboLibrary
//
//  Created by jianghui liu on 2022/5/7.
//

import Foundation
import UIKit
import RxCocoa
import RxSwift
import SnapKit


class LoadingAlert : UIView {
    var cancelEvent : BehaviorSubject<Void> = BehaviorSubject(value: ())
    let bag = DisposeBag()
    
    lazy var loadingActivity : UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(style: .large)
        self.addSubview(view)
        view.snp.makeConstraints { make in
            make.center.equalTo(self)
        }
        return view
    }()
    lazy var cancelBtn : UIButton = {
        let btn = UIButton(type: .system)
        btn.setTitle("取消", for: .normal)
        btn.backgroundColor = .white
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 5.0
        btn.setTitleColor(.black, for: .normal)
        self.addSubview(btn)
        btn.snp.makeConstraints { make in
            make.top.equalTo(loadingActivity.snp.bottom)
            make.centerX.equalTo(self)
            make.width.equalTo(70)
            make.height.equalTo(40)
        }
        
        return btn
    }()
    
    static func showAbove(view : UIView) -> LoadingAlert {
        let alert = LoadingAlert(frame: view.bounds)
        view.addSubview(alert)
        alert.loadingActivity.startAnimating()
        return alert
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        self.backgroundColor = UIColor(displayP3Red: 200, green: 200, blue: 200, alpha: 0.5)
        cancelBtn.rx.tap.throttle(.milliseconds(100), scheduler: MainScheduler.instance)
            .subscribe(onNext: { [weak self] in
                self?.cancelEvent.onNext(())
                self?.removeFromSuperview()
            }).disposed(by: bag)
    }
}
