//
//  WebView.swift
//  Sailassist
//
//  Created by Mamoru Sugita on 2023/11/22.
//

import SwiftUI
import WebKit

struct WebView: UIViewRepresentable {
    @Binding var isLoading: Bool
    var url : String

    func makeUIView(context: Context) -> WKWebView {
        let request = URLRequest(url: URL(string: url)!)
        let webView = WKWebView()
        webView.navigationDelegate = context.coordinator
        webView.load(request)
        return webView
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {}

    func makeCoordinator() -> Coordinator {
        return Coordinator(owner: self)
    }
    
    class Coordinator: NSObject, WKNavigationDelegate {
        private let owner: WebView

        init(owner: WebView) {
            self.owner = owner
            super.init()
        }

        func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
            owner.isLoading = true
        }

        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            owner.isLoading = false
        }
    }
}

#Preview {
    WebView(isLoading: .constant(false), url: "https://ssv-canary-web.azurewebsites.net/login?ReturnUrl=%2F")
}
