//
//  FindOnPageViewController.swift
//  App
//
//  Created by James Magahern on 9/30/20.
//

import UIKit

class FindOnPageViewController: UIViewController, _WKFindDelegate
{
    static func isEnabled() -> Bool {
        if #available(iOS 16.0, *) {
            return false
        }
        
        return true
    }
    
    let findOnPageView = FindOnPageView()
    weak var webView: WKWebView? {
        didSet { webView?._findDelegate = self }
    }
    
    private var findString: String?
    private let findOptions: _WKFindOptions = [
        .caseInsensitive,
        .atWordStarts,
        .treatMedialCapitalAsWordStart,
        .wrapAround,
        .showFindIndicator,
        .showOverlay,
        .showHighlight,
        .determineMatchIndex,
    ]
    
    private let maxCount: UInt = 1000
    
    convenience init() {
        self.init(nibName: nil, bundle: nil)
        
        findOnPageView.textField.addAction(UIAction(handler: { [unowned self] _ in
            self.findString = findOnPageView.textField.text
            webView?._find(self.findString, options: self.findOptions, maxCount: UInt(self.maxCount))
        }), for: .editingChanged)
        
        findOnPageView.prevResultButton.addAction(UIAction(handler: { [unowned self] _ in
            findPrevious(nil)
        }), for: .touchUpInside)
        
        findOnPageView.nextResultButton.addAction(UIAction(handler: { [unowned self] _ in
            findNext(nil)
        }), for: .touchUpInside)
        
        findOnPageView.doneButton.addAction(UIAction(handler: { [unowned self] _ in
            doneFinding(nil)
        }), for: .touchUpInside)
        
        // Escape to cancel
        addKeyCommand(UIKeyCommand(input: UIKeyCommand.inputEscape, modifierFlags: [], action: #selector(Self.doneFinding)))
        
        // Return goes to next
        addKeyCommand(UIKeyCommand(input: "\n", modifierFlags: [], action: #selector(Self.findNext)))
        
        // Cmd+G next
        addKeyCommand(UIKeyCommand(input: "G", modifierFlags: [.command], action: #selector(Self.findNext)))
        
        // Shift return goes to prev
        addKeyCommand(UIKeyCommand(input: "\n", modifierFlags: [.shift], action: #selector(Self.findPrevious)))
        
        // Shift+Cmd+G prev
        addKeyCommand(UIKeyCommand(input: "G", modifierFlags: [.command, .shift], action: #selector(Self.findPrevious)))
        
        self.view = findOnPageView
    }
    
    @objc
    func doneFinding(_ sender: Any?) {
        findOnPageView.textField.resignFirstResponder()
        webView?._hideFindUI()
    }
    
    @objc
    override func findNext(_ sender: Any?) {
        webView?._find(self.findString, options: self.findOptions, maxCount: UInt(self.maxCount))
    }
    
    @objc
    override func findPrevious(_ sender: Any?) {
        let options: _WKFindOptions = self.findOptions.union(.backwards)
        webView?._find(self.findString, options: options, maxCount: UInt(self.maxCount))
    }
    
    func _webView(_ webView: WKWebView!, didFailToFind string: String!) {
        // ??
    }
        
    internal func _webView(_ webView: WKWebView!, didFindMatches matches: UInt, for string: String!, withMatch matchIndex: Int) {
        findOnPageView.nextResultButton.isEnabled = matches > 0
        findOnPageView.prevResultButton.isEnabled = matches > 0
    }
}
