//
//  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 {
        var address: URL
        if url.contains("https://") {
            address = URL(string: url)!
        } else {
            address = URL(fileURLWithPath: url)
        }
        let request = URLRequest(url: address)
        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://www.jmarinecloud.com/eng/contact.php?type=ssv_mobile")
}
