//
//  LLQ_SearchTextView.swift
//  PrivateBrowser
//
//  Created by MAC on 2022/6/9.
//

import UIKit
import RxRelay
import RxSwift
import RxCocoa

class LLQ_SearchTextView: UIView {
    enum RightButtonResponseType {
        case search
        case refresh
        case textviewBecomActive
    }
    @IBOutlet var contentView: UIView!
    @IBOutlet weak var homeButton: UIButton!
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var tfLeadingConstraint: NSLayoutConstraint!
    private lazy var disposeBg = DisposeBag()
    
    private lazy var rightButton: UIButton = {
        let button = UIButton.init(type: .custom)
        button.setImage(UIImage.init(named: "icon_textview_serarch"), for: .normal)
        button.setImage(UIImage.init(named: "icon_textview_refresh"), for: .selected)
        button.backgroundColor = UIColor.init(hexString: "#242424")
        return button
    }()
    
    private lazy var leftView: UIView = {
       let view = UIView()
        
        return view
    }()


    var style: HomePageStyle = .idle
    var viewModel: LLQ_HomeViewModel?
    
//    var style: Style = .idle{
//        didSet {
//            if oldValue == .idle && style == .edit {
//                
//            } else if oldValue == .edit && style == .searched {
//                
//            } else {
//                
//            }
//            self.rightButton.isSelected = style == .searched
//            
//        }
//    }
    
    func setViewModel(viewModel: LLQ_HomeViewModel) {
        self.viewModel = viewModel
        
        // UI
        let uiChange: Binder<HomePageStyle> = Binder<HomePageStyle>.init(self, scheduler: MainScheduler.asyncInstance) { view, style in
            switch style {
            case .idle:
                view.tfLeadingConstraint.constant = 0
                view.homeButton.alpha = 0
                view.homeButton.isUserInteractionEnabled = false
                view.rightButton.isSelected = false
            case .editingSearch:
                view.tfLeadingConstraint.constant = 0
                view.homeButton.alpha = 0
                view.homeButton.isUserInteractionEnabled = false
                view.rightButton.isSelected = false
            case .searched:
                view.tfLeadingConstraint.constant = 44.5
                view.homeButton.alpha = 1
                view.homeButton.isUserInteractionEnabled = true
                view.rightButton.isSelected = true
            }
            view.style = style
        }
        self.viewModel?.styleStream.asObservable().distinctUntilChanged().bind(to: uiChange).disposed(by: disposeBg)
        
        self.homeButton.rx.tap.subscribe { [weak self] _ in
            self?.viewModel?.resetHomePage()
        }.disposed(by: disposeBg)
        
        self.viewModel?.editingStream.asObservable().subscribe({[weak self] event in
            switch event {
            case .next(let editing):
                if editing {
                    self?.textField.becomeFirstResponder()
                } else {
                    self?.textField.resignFirstResponder()
                }
                break
            default:
                break
            }
        }).disposed(by: disposeBg)
        
        self.viewModel?.textFieldUpdateTextStream.asObservable().subscribe({ [weak self] event in
            switch event {
            case .next(let str):
                if str.count == 0 {
                    self?.textField.text = str
                    return
                }
                if self?.viewModel?.styleStream.value == .searched, str.count > 0 {
                    self?.textField.text = str
                }
                break
            default:
                break
            }
        }).disposed(by: disposeBg)
        
        self.textField.rx.text.orEmpty.asObservable().bind(to: Binder<String>.init(self, scheduler: MainScheduler.asyncInstance, binding: { view, text in
            guard view.viewModel?.styleStream.value == .searched else {return}
            guard let singleVm = view.viewModel?.getActiveVM() else {return}
            if view.textField.text == singleVm.urlString {
                view.rightButton.isSelected = true
            } else {
                view.rightButton.isSelected = false
            }
        })).disposed(by: disposeBg)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()

        self.textField.layer.cornerRadius = self.bounds.size.height / 2
        rightButton.snp.remakeConstraints { make in
            make.size.equalTo(CGSize.init(width: 57, height: self.bounds.size.height))
        }
        leftView.snp.remakeConstraints { make in
            make.size.equalTo(CGSize.init(width: 20, height: self.bounds.height))
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        Bundle.main.loadNibNamed("LLQ_SearchTextView", owner: self, options: nil)
        self.addSubview(contentView)
        contentView.backgroundColor = UIColor(red: 0.941, green: 1, blue: 0.808, alpha: 1)
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        self.textField.rightView = self.rightButton
        self.textField.rightViewMode = .always
        self.textField.leftView = self.leftView
        self.textField.leftViewMode = .always
        self.textField.layer.masksToBounds = true
        self.textField.clearButtonMode = .always
        self.textField.delegate = self
        
 
                
        
        self.homeButton.rx.tap.subscribe {[weak self] _ in
            self?.viewModel?.resetHomePage()
        }.disposed(by: disposeBg)
        
        
        // rightButton
        self.rightButton.rx.tap.map {[weak self] _ -> RightButtonResponseType in
            if self?.style == .idle {
                return RightButtonResponseType.textviewBecomActive
            } else if self?.style == .editingSearch {
                return RightButtonResponseType.search
            } else {
                return RightButtonResponseType.refresh
            }
        }.subscribe { [weak self] event in
            switch event {
            case .next(let responseType):
                if responseType == .textviewBecomActive {
                    self?.textField.becomeFirstResponder()
                    self?.rightButton.isSelected = false
                } else if responseType == .search {
                    guard let searchText = self?.textField.text, searchText.count > 0 else {return}
                    self?.viewModel?.openWeb(urlString: searchText)
                    self?.rightButton.isSelected = false
                } else if responseType == .refresh {
                    guard let singleVm = self?.viewModel?.getActiveVM() else {return}
                    guard let searchText = self?.textField.text, searchText.count > 0 else {return}
                    self?.viewModel?.refreshWebView(newUrlString: searchText)
                    self?.rightButton.isSelected = true
                }
                break
            default:
                break
            }
        }.disposed(by: disposeBg)
    }
}

extension LLQ_SearchTextView: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if self.style == .idle {
            self.textField.text = ""
            NSLog("---  set text to nil ")
            self.viewModel?.setStyleStream(toStyle: .editingSearch)
        }
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if self.style == .editingSearch {
            guard let text = textField.text, text.count > 0 else {
                return false
            }
            self.viewModel?.openWeb(urlString: text)
        } else if self.style == .searched {
            if let text = self.textField.text, text.count > 0{
                self.viewModel?.refreshWebView(newUrlString: text)
            } else {
                self.viewModel?.refreshWebView(newUrlString: nil)
            }
        }
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        
    }
}
