//
//  SignalRService.swift
//  Sailassist
//
//  Created by 三浦薫巳 on 2023/11/17.
//

import Foundation
import SwiftSignalRClient

public class SignalRService {
    private var connection: HubConnection

    public init(url: URL) {
        // リクエストURLの組み立て
//        let url_string : String = HttpRequestType.SignalR.rawValue
//        guard let req_url = URL(string : url_string) else {
//            return
//        }
        connection = HubConnectionBuilder(url: url).withLogging(minLogLevel: .error).build()
        connection.on(method: "MessageReceived", callback: { (user: String, message: String) in
            do {
                self.handleMessage(message, from: user)
            } catch {
                print(error)
            }
        })

//        hubConnection?.invoke(method: "Your Method Name", arguments: [arg1, arg2]) { error in
//                    if let error = error {
//                        print("An error occurred: %@", "\(error)")
//                    }
//        }
//
//        hubConnection?.on(method: "YourMethod", callback: { (chatCount: Int, notificationsCount: Int) in
//                    self.notificationCount = notificationsCount
//                    self.chatCount = chatCount
//                })

        connection.start()
    }

    private func handleMessage(_ message: String, from user: String) {
        // Do something with the message.
    }

    func connectionDidOpen(hubConnection: SwiftSignalRClient.HubConnection) {
        print("connectionDidOpen")
        // After connection established call registerUserInServer method
            DispatchQueue.main.async {
//                self.registerUserInServer()
            }
    }

    func connectionDidFailToOpen(error: Error) {
        print("connectionDidFailToOpen")
    }

    func connectionDidClose(error: Error?) {
        print("connectionDidClose")
    }

    func connectionWillReconnect(error: Error) {
        print("connectionWillReconnect")
    }

    func connectionDidReconnect() {
        print("connectionDidReconnect")
    }
}
