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

import Foundation
import RxRelay
import RxCocoa
enum HomePageStyle {
    case idle
    case editingSearch
    case searched
}

enum HomeActionType {
    case Instagram
    case Vimeo
    case Tiktok
    case Facebook
    
    var url : String {
        switch self {
        case .Instagram:
            return "https://www.instagram.com/"
        case .Vimeo:
            return "https://vimeo.com/"
        case .Tiktok:
            return "https://www.tiktok.com/"
        case .Facebook:
            return "https://www.facebook.com/"
        }
    }
}

class LLQ_HomeSinglePageViewModel {
    var webViewTag: Int
    var urlString: String
    var deleteStream: PublishRelay<Bool> = PublishRelay.init()
    var snapScreenImage: UIImage?
    
    var goPreviouseStream: PublishRelay<Bool> = PublishRelay<Bool>.init()
    var goForwardStream: PublishRelay<Bool> = PublishRelay<Bool>.init()
    var goHomeStream: PublishRelay<Bool> = PublishRelay<Bool>.init()
    var mutiWindowsStream : PublishRelay<Bool> = PublishRelay<Bool>.init()
    
    var snpShotStream: PublishRelay<LLQ_HomeSinglePageViewModel> = PublishRelay<LLQ_HomeSinglePageViewModel>.init()
    
    var refreshWebStream = PublishRelay<String>.init()
    var startLoadUrlStringStream = PublishRelay<String>.init()
    
    var openNewWebStream = PublishRelay<String>.init()
    
    var textFieldUpdateTextStream = PublishRelay<String>.init()
    init(urlString: String, webViewTag: Int){
        self.urlString = urlString
        self.webViewTag = webViewTag
    }
    
    func snapShot() {
        self.snpShotStream.accept(self)
    }
    
}

class LLQ_HomeViewModel {
    var searchText: String = ""

    var lastHomeStyle: HomePageStyle = .idle
    var styleStream: BehaviorRelay<HomePageStyle> = BehaviorRelay.init(value: .idle)
    var editingStream: PublishRelay<Bool> = PublishRelay.init()

    var viewModels: [LLQ_HomeSinglePageViewModel] = [LLQ_HomeSinglePageViewModel]() {
        didSet {
            self.mutiWinowEnableStream.accept(viewModels.count > 0)
        }
    }
    
    var mutiWinowEnableStream = BehaviorRelay<Bool>.init(value: false)
    // pages
    var addPageStream: PublishRelay<LLQ_HomeSinglePageViewModel> = PublishRelay<LLQ_HomeSinglePageViewModel>()
    var toListControllerStream: PublishRelay<Bool> = PublishRelay<Bool>.init()
    var switchToWebPageStream: PublishRelay<LLQ_HomeSinglePageViewModel> = PublishRelay<LLQ_HomeSinglePageViewModel>.init()
    var deleteWebPageStream = PublishRelay<LLQ_HomeSinglePageViewModel>.init()
    var activeWebViewTag: Int = 0
    
    // textField
    var textFieldUpdateTextStream = PublishRelay<String>.init()
    
    
    
    public func setStyleStream(toStyle: HomePageStyle) {
        switch toStyle {
        case .idle:
            self.endEditing()
            break
        case .editingSearch:
            self.beginEditing()
            break
        case .searched:
            self.endEditing()
            break
        }
        self.styleStream.accept(toStyle)
        self.lastHomeStyle = toStyle

    }
    

    
    public func startLoad(urlString: String) {
        func getMaxTag()-> Int {
            var index = 1000 - 1
            self.viewModels.forEach { m in
                if m.webViewTag > index {
                    index = m.webViewTag
                }
            }
            return index
        }
        let tag =  getMaxTag() + 1
        let singleVM = LLQ_HomeSinglePageViewModel.init(urlString: urlString, webViewTag: tag)
        self.activeWebViewTag = tag
        self.addPageStream.accept(singleVM)
        

        
        self.viewModels.append( singleVM)
    }
    
    
    public func resetHomePage(){
        self.setStyleStream(toStyle: .idle)
        self.textFieldUpdateTextStream.accept("")
    }
    
    public func resetHomePageAndDeleteWeb(){
        self.setStyleStream(toStyle: .idle)
        if let singleVm = self.getActiveVM() {
            singleVm.deleteStream.accept(true)
        }
        
    }
    

    
    public func endEditing(){
        self.editingStream.accept(false)
    }
    
    public func beginEditing(){
        self.editingStream.accept(true)
    }
    
    func getActiveVM() -> LLQ_HomeSinglePageViewModel?{
        for vm in self.viewModels {
            if vm.webViewTag == self.activeWebViewTag {
                return vm
            }
        }
        return nil
    }
}

extension LLQ_HomeViewModel {
    public func openWeb(type: HomeActionType) {
        self.setStyleStream(toStyle: .searched)
        self.startLoad(urlString: type.url)
        self.textFieldUpdateTextStream.accept(type.url)
    }
    
    public func openWeb(urlString: String) {
        var urlString = urlString
        if urlString.isHttpURL() {
         
        } else if urlString.isDomain() {
            urlString = "https://\(urlString))"
        } else {
            var searchComponent = URLComponents(string: "https://www.google.com/search")
            let queryItems = URLQueryItem(name: "q", value: urlString)
            searchComponent?.queryItems = [queryItems]
            guard let str = searchComponent?.url?.absoluteString else {
                return
            }
            urlString = str
        }
        self.setStyleStream(toStyle: .searched)
        self.startLoad(urlString: urlString)
        self.textFieldUpdateTextStream.accept(urlString)
    }
    
    public func switchTo(singleVm: LLQ_HomeSinglePageViewModel) {
        self.setStyleStream(toStyle: .searched)
        self.switchToWebPageStream.accept(singleVm)
        self.activeWebViewTag = singleVm.webViewTag
        self.textFieldUpdateTextStream.accept(singleVm.urlString)
    }
    
    public func deleteWebPage(singleVm: LLQ_HomeSinglePageViewModel){
        self.deleteWebPageStream.accept(singleVm)
        self.viewModels.removeAll { $0.webViewTag == singleVm.webViewTag }
        if self.activeWebViewTag == singleVm.webViewTag {
            if let first = self.viewModels.first {
                self.activeWebViewTag = first.webViewTag
                self.switchTo(singleVm: first)
            } else {
                self.activeWebViewTag = 0
                self.resetHomePage()
            }
        } else {
            // do noting
        }
    }
    
    public func refreshWebView(newUrlString: String? = nil){
        self.editingStream.accept(false)
        guard let singleVM = self.getActiveVM() else {
            return
        }
        if let newUrlString = newUrlString {
            var urlString = newUrlString
            if urlString.isHttpURL() {
             
            } else if urlString.isDomain() {
                urlString = "https://\(urlString))"
            } else {
                var searchComponent = URLComponents(string: "https://www.google.com/search")
                let queryItems = URLQueryItem(name: "q", value: urlString)
                searchComponent?.queryItems = [queryItems]
                guard let str = searchComponent?.url?.absoluteString else {
                    return
                }
                urlString = str
            }
            singleVM.refreshWebStream.accept(urlString)
        } else {
            singleVM.refreshWebStream.accept(singleVM.urlString)
        }
    }
}
