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

import Foundation
import SwiftSignalRClient

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

    public init() {
        //        hubConnectionDelegate = ChatHubConnectionDelegate(app: self)
        hubConnectionDelegate = ChatHubConnectionDelegate()
        connection = HubConnectionBuilder(url: URL(string : HttpRequestType.SignalR.rawValue)!)
            .withHubConnectionDelegate(delegate: hubConnectionDelegate!)
            .withAutoReconnect()
            .withLogging(minLogLevel: .error).build()

        connection.on(method: "chatMessage", callback: { (shipId: Int, messageId: Int, type: Int, time: String, location: Int, from: String, fromeId: Int, message: String) in
            self.handleChatMessage(message, from: from)
        })

        connection.on(method: "ackMessage", callback: { (shipId: Int, time: String, location: Int, fromId: Int, mode: Int) in
            self.handleAckMessage(time)
        })

        connection.on(method: "chatMode", callback: { (shipId: Int, time: String, location: Int, fromId: String, mode: Int) in
            self.handleChatMessage(fromId)
        })

        connection.start()
    }

    private func handleChatMessage(_ message: String, from user: String) {
        print(debug: "called")
    }

    private func handleAckMessage(_ time: String) {
        print(debug: "called")
    }

    private func handleChatMessage(_ fromId: String) {
        print(debug: "called")
    }

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

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

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

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

    func chatMode(_ message: String) {
        var request = ReqChatModeMessage(shipId: Preferences.shipId)
        //        request.time = DateTextLib.Date2ISO8601Text(date: Date())
        request.location = 2                //1:Shore , 2:Ship
        //        request.fromeId = SharingData.my.shipName //ユーザーID
        request.mode = 0       //0:通常 / 1:Warning中
        if message != "" {
            connection.invoke(method: "ChatMode", message) { 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: AppDelegate?
//
//    init(app: AppDelegate) {
//        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")
    }
}
