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

import Foundation
import SwiftSignalRClient

class SignalRService: ObservableObject{
    private var connection: HubConnection
    private var hubConnectionDelegate: HubConnectionDelegate?

    public init() {
//        hubConnectionDelegate = ChatHubConnectionDelegate(controller: self)
        hubConnectionDelegate = ChatHubConnectionDelegate()
        connection = HubConnectionBuilder(url: URL(string : HttpRequestType.SignalR.rawValue)!)
            .withHubConnectionDelegate(delegate: hubConnectionDelegate!)
            .withAutoReconnect()
            .withLogging(minLogLevel: .error)
            .withHubConnectionOptions(configureHubConnectionOptions: {options in options.keepAliveInterval = 20 })
            .build()

        connection.on(method: "chatMessage", callback: { (message: ResChatMessage) in
            self.handleChatMessage(message: message)
        })

        connection.on(method: "ackMessage", callback: { (message: ResAckMessage) in
            self.handleAckMessage(message: message)
        })

        connection.on(method: "chatMode", callback: { (message: ResChatMode) in
            self.handleChatMessage(message: message)
        })

        connection.start()
    }

    private func handleChatMessage(message: ResChatMessage) {
        print(debug: "called")
    }

    private func handleAckMessage(message: ResAckMessage) {
        print(debug: "called")
    }

    private func handleChatMessage(message: ResChatMode) {
        print(debug: "called")
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        connection.stop()
    }

    //呼び出す
    func chatMessage(message: String) {
        var request = ReqMessage(shipId: Preferences.shipId, messageId: UUID().uuidString)
        request.type = 0                    //0:テキスト, 1:スタンプ
        request.time = DateTextLib.Date2ISO8601Text(Date())
        request.location = 2                //1:Shore , 2:Ship
        request.from = Preferences.UserName //投稿者名
        request.fromeId = SharingData.my.id //ユーザーID
        request.message = message           //テキスト
//        request.stampId = //スタンプ番号 0:Fire～

        if message != "" {
            connection.invoke(method: "chatMessage", request) { error in
                if let e = error {
                    print(debug: "Error:\(e)")
                }
            }
        }
    }

    func ackMessage(messageId: String) {
        var request = ReqAckMessage(shipId: Preferences.shipId, messageId: messageId)
        request.time = DateTextLib.Date2ISO8601Text(Date())
        request.location = 2                //1:Shore , 2:Ship
        request.fromeId = SharingData.my.id //ユーザーID
        if messageId != "" {
            connection.invoke(method: "ackMessage", request) { error in
                if let e = error {
                    print(debug: "Error:\(e)")
                }
            }
        }
    }

    func chatMode() {
        var request = ReqChatModeMessage(shipId: Preferences.shipId)
        request.time = DateTextLib.Date2ISO8601Text(Date())
        request.location = 2                //1:Shore , 2:Ship
        request.fromeId = SharingData.my.id //ユーザーID
        request.mode = 0       //0:通常 / 1:Warning中
        connection.invoke(method: "chatMode", request) { error in
            if let e = error {
                print(debug: "Error:\(e)")
            }
        }
    }

//    func chatMode2(_ message: String) {
//        connection.send(method: "Broadcast", "Playground user", "Testing send") { error in
//            if let error = error {
//                print("Send failed: \(error)")
//            }
//        }
//    }
}

class ChatHubConnectionDelegate: HubConnectionDelegate {
//    weak var app: SignalRService?
//
//    init(app: SignalRService) {
//        self.app = app
//    }

    //接続が正常に開始されたときに発生
    func connectionDidOpen(hubConnection: 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")
    }
}
