//
//  GetMessage.swift
//  Sailassist
//
//  Created by 三浦薫巳 on 2023/11/14.
//

import Foundation

class GetMessage {
    var sessionGetMessage = SessionGetMessage()

    func start() {
        print(debug: "called")
        sessionGetMessage.RequestGetMessage { response in
            switch response {
            case .success(let resultData):
                let serverSession = ServerSession()
                let resjson = serverSession.fromJSON(resultData: resultData, resltType: ResGetMessages.self)
                if let res = resjson {
                    if res.mode == 1 {
                        SharingData.message.mode = true
                    } else {
                        SharingData.message.mode = false
                    }
                    SharingData.message.messages = []
                    if let msg = res.messages {
                        //既読マーク確認
                        SharingData.message.messages = msg
                        self.checkUnreadMessages()
                    }
                    SharingData.message.users = []
                    if let users = res.users {
                        SharingData.message.users = users
                    }
                }
            case .failure(let errorCode):
                print(debug: errorCode)
                break
            }
        }
    }

    /**
     * 未読数の確認
     */
    func checkUnreadMessages() {
        var msgCnt = 0      //SSV Mobileからの受信メッセージ数
        var viewCnt = 0     //Sail Assistでの既読メッセージ数

        for message in SharingData.message.messages {
            //SSV Mobileからの受信メッセージ
            msgCnt = msgCnt + 1
            if ((message.viewer.first(where: {$0.id == String(SharingData.my.id)})) != nil){
                viewCnt = viewCnt + 1
            }
        }

//        SharingData.message.viewCnt = msgCnt - viewCnt  //未読数
    }

    /**
     * 既読通知
     */
    func readNotification() {
//        let id = SharingData.my.id
//        let msg = SharingData.message.messages
        for message in SharingData.message.messages {
            //Sail Assist側で既読が無い場合（既読確認）
            var unRead = true
            if ((message.viewer.first(where: {$0.id == String(SharingData.my.id)})) != nil) {
                unRead = false  //既読状態
            }

            if unRead {
                let signalRService = SignalR()
                signalRService.ackMessage(messageId: message.messageId) { error in
                    if let e = error {
                        print(debug: "error chat:\(e)")
                    } else {
                        let msgIndex = SharingData.message.messages.firstIndex(where: {$0.messageId == message.messageId})
                        if let index = msgIndex {
                            let viewer = Viewer(time: DateTextLib.Date2ISO8601Text(Date()), location: 2, id: String(SharingData.my.id))
                            SharingData.message.messages[index].viewer.append(viewer)
                        }
                    }
                }
            }
        }
    }
}

