//
//  LLQ_HomeWebContainerView.swift
//  PrivateBrowser
//
//  Created by MAC on 2022/6/13.
//

import Foundation
import UIKit
import WebKit
import RxSwift
class LLQ_HomeWebContainerView : UIView {
    lazy var progressView : UIProgressView = {
        let progressView = UIProgressView.init()
        return progressView
    }()
    private var configuration: WKWebViewConfiguration
    var singleVM: LLQ_HomeSinglePageViewModel
    private var disposeBg = DisposeBag()
    var webView: LLQ_WebView
    
    weak var superV: UIView?
    
    private lazy var bottomBar: LLQ_HomeWebBar = {
        let bottomBar = Bundle.main.loadNibNamed("LLQ_HomeWebBar", owner: self, options: nil)?.first as! LLQ_HomeWebBar
        bottomBar.previousButton.rx.tap.map { _ in
            return true
        }.bind(to: self.singleVM.goPreviouseStream).disposed(by: disposeBg)
        
        bottomBar.forwardButton.rx.tap.map { _ in
            return true
        }.bind(to: self.singleVM.goForwardStream).disposed(by: disposeBg)
        
        bottomBar.windowsButton.rx.tap.map { _ in
            return true
        }.bind(to: self.singleVM.mutiWindowsStream).disposed(by: disposeBg)
        
        bottomBar.homeButton.rx.tap.map { _ in
            return true
        }.bind(to: self.singleVM.goHomeStream).disposed(by: disposeBg)
        return bottomBar
    }()
    

    init(frame: CGRect, vm: LLQ_HomeSinglePageViewModel, configuration: WKWebViewConfiguration) {
        self.configuration = configuration
        self.singleVM = vm
        self.webView = LLQ_WebView.init(frame: .zero, configuration: self.configuration, singleVm: vm)

        super.init(frame: frame)
        self.set()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate func set(){
        // UI
        self.addSubview(self.progressView)
        progressView.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.height.equalTo(1)
        }

        self.bringSubviewToFront(progressView)
        self.addSubview(self.bottomBar)
        bottomBar.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.height.equalTo(20).priority(.low)
        }
        
        self.addSubview(webView)
        webView.snp.makeConstraints { make in
            make.leading.trailing.top.equalToSuperview()
            make.bottom.equalTo(bottomBar.snp.top)
        }
        self.bringSubviewToFront(self.progressView)
        
        // refresh
        self.singleVM.refreshWebStream.asObservable().bind(to: Binder<String>.init(self, scheduler: MainScheduler.asyncInstance, binding: { view, urlString in
            guard let url = URL.init(string: urlString) else {return}
            view.webView.load(URLRequest.init(url: url))
        })).disposed(by: disposeBg)
        
        // loading
        
        webView.rx.observe(Bool.self, "canGoBack").map({ return $0 ?? false
        }).bind(to: self.bottomBar.previousButton.rx.isEnabled).disposed(by: disposeBg)
        webView.rx.observe(Bool.self, "canGoForward").map({ return $0 ?? false
        }).bind(to: self.bottomBar.forwardButton.rx.isEnabled).disposed(by: disposeBg)
        
        self.bottomBar.previousButton.rx.tap.bind(to: Binder<Void>.init(self, scheduler: MainScheduler.asyncInstance, binding: { view, _ in
            view.webView.goBack()
        })).disposed(by: disposeBg)
        
        self.bottomBar.forwardButton.rx.tap.bind(to: Binder<Void>.init(self, scheduler: MainScheduler.asyncInstance, binding: { view, _ in
            view.webView.goForward()
        })).disposed(by: disposeBg)
        
        // Progress
        webView.rx.observe(Double.self, "estimatedProgress").subscribe {[weak self] progress in
            switch progress {
            case .next(let progress):
                self?.progressView.isHidden = (progress ?? 0) >= 1
                self?.progressView.progress = Float(progress ?? 0)
                break
            default:
                break
            }
        }.disposed(by: disposeBg)
        
        // snapShot
        self.singleVM.snpShotStream.asObservable().subscribe {[weak self] event in
            switch event {
            case .next(let vm):
                if let image = self?.snapShot() {
                    vm.snapScreenImage = image
                }
                break
            default:
                break
            }
        }.disposed(by: disposeBg)
        
        guard let url = URL.init(string: self.singleVM.urlString) else {return}
        self.webView.load(URLRequest.init(url: url))
        
        
        

    }
    
    func snapShot() -> UIImage?{
        
//            UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.main.scale)
//            self.drawHierarchy(in: self.bounds, afterScreenUpdates: false)
//            let image = UIGraphicsGetImageFromCurrentImageContext()
//            UIGraphicsEndImageContext()
//        
//        
////        let image = UIImage(named: "launch_top_bg")
//            return image

        let renderer = UIGraphicsImageRenderer(size: self.bounds.size)
         let image = renderer.image { _ in
             self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
         }
         return image
    }
}

