import Foundation
import UIKit
import WebKit

/// delegate protocol for sign in view
protocol SignInViewDelegate: AnyObject {
    func successLogIn(token: String)
}

/// sign in view
class SingInView: UIView {
    
    weak var delegate: SignInViewDelegate?
    
    private let webView = WKWebView()
    
    private let url = URL(string: "\(SERVER_URL)Login/?appid=\(APP_ID)")!
    
    /// initialization function
    /// - Parameter frame: frame
    override init(frame: CGRect) {
        super.init(frame: frame)
        webView.load(URLRequest(url: url))
        webView.translatesAutoresizingMaskIntoConstraints = false
        webView.navigationDelegate = self
        addSubview(webView)
        setupConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// function for setting up constraints for view elements
    private func setupConstraints() {
        NSLayoutConstraint.activate([
            webView.leadingAnchor.constraint(equalTo: leadingAnchor),
            webView.topAnchor.constraint(equalTo: topAnchor),
            webView.trailingAnchor.constraint(equalTo: trailingAnchor),
            webView.bottomAnchor.constraint(equalTo: bottomAnchor)
        ])
    }
    
    /// function for getting the web view content and sets the id
    private func getContent() {
        webView.evaluateJavaScript("document.getElementsByName('skautIS_IDUnit')[0].value", completionHandler: { (value: Any!, error: Error!) -> Void in
            if error != nil {
                return
            }
            guard let result = value as? String else { return }
            UserDefaults.unitId = result
        })
        webView.evaluateJavaScript("document.getElementsByName('skautIS_Token')[0].value", completionHandler: { (value: Any!, error: Error!) -> Void in
            if error != nil {
                return
            }
            guard let result = value as? String else { return }
            self.delegate?.successLogIn(token: result)
        })
    }
}

extension SingInView: WKNavigationDelegate {
    
    /// webview delegate function for navigation
    /// - Parameters:
    ///   - webView: web view
    ///   - navigationResponse: navigation response
    ///   - decisionHandler: decision handler
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        if (navigationResponse.response.url?.absoluteString == "\(SERVER_URL)Login/LoggedIn.aspx") {
            getContent()
            decisionHandler(.cancel)
        } else {
            decisionHandler(.allow)
        }
    }
}
