// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

import Foundation
import WebKit
import SnapKit

class FAQController: UIViewController {
    fileprivate let theme: Theme
    fileprivate let webConfiguration = WKWebViewConfiguration()
    fileprivate var webView: WKWebView!
    fileprivate var spinner: UIActivityIndicatorView!

    init(theme: Theme) {
        self.theme = theme
        super.init(nibName: nil, bundle: nil)

        hidesBottomBarWhenPushed = true
        title = String(localized: "settings_faq")
    }

    required convenience init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func loadView() {
        loadViewWithBackgroundColor(theme.colorForType(.NormalBackground))

        createViews()
        installConstraints()
    }

    override func viewDidLoad() {
        webView.configuration.preferences.javaScriptEnabled = true
        super.viewDidLoad()
        let contentController = self.webView.configuration.userContentController
        contentController.add(self, name: "addSupportToxID")

        let url = Bundle.main.url(forResource: "FAQ_en", withExtension: "html")
        let request = NSURLRequest(url: url!)
        webView.load(request as URLRequest)
    }
    
}

extension FAQController: WKScriptMessageHandler{
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        // TODO(Tha_14): Change this so that we use the button to instead immediately add the friend. We need to carry the ToxManager object from the tab controller into the settings coordinator
        UIPasteboard.general.string = "0525CEA07DC84D4CEF9154FB785344D573CD558140BEC7216845FDAC77FFEF7A993E21186874"
        let alertController = UIAlertController(title: "ToxID copied to clipboard. Head to Contacts in Antidote and paste it in the Add Contact page.",message: nil,preferredStyle:
        .alert)

        alertController.addAction(UIAlertAction(title: "OK", style: .cancel) {_ in })

        self.present(alertController, animated: true, completion: nil)
//        let message:String? = "Requesting Antidote support."
//        let supportcontactid:String? = "0525CEA07DC84D4CEF9154FB785344D573CD558140BEC7216845FDAC77FFEF7A993E21186874"
//        do {
//            try submanagerFriends.sendFriendRequest(toAddress: supportcontactid, message: message)
//        }
//        catch _ as NSError {
//            return
//        }
        
        print("Adding support contact")
    }
}

extension FAQController: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        spinner.startAnimating()
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        spinner.stopAnimating()
    }
}

extension FAQController {
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message:
    String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () ->
    Void) {
    let alertController = UIAlertController(title: message,message: nil,preferredStyle:
    .alert)

    alertController.addAction(UIAlertAction(title: "OK", style: .cancel) {_ in
    completionHandler()})

    self.present(alertController, animated: true, completion: nil)
    }
}

private extension FAQController {
    func createViews() {
        let configuration = WKWebViewConfiguration()

        webView = WKWebView(frame: CGRect.zero, configuration: configuration)
        webView.navigationDelegate = self
        view.addSubview(webView)

        spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        spinner.hidesWhenStopped = true
        view.addSubview(spinner)
    }

    func installConstraints() {
        webView.snp.makeConstraints {
            $0.edges.equalTo(view)
        }

        spinner.snp.makeConstraints {
            $0.center.equalTo(view)
        }
    }
}
