//
//  IMRemoteUtil.swift

//
//  Created by Leon on 2025/8/18.
//

import NIMSDK
import UIKit
class IMRemoteUtil {
    /// V2NIMMessage -> IMBaseRemoteInfo 初步划分确定 消息划分的cellType
    static func dealRemoteInfo(message: V2NIMMessage?) -> IMBaseRemoteInfo {
        guard let msg = message else {
            return IMBaseRemoteInfo()
        }

        // Parse serverExtension
        let remote = message?.serverExtension ?? ""
        let info = CodableHelper.decode(IMBaseRemoteInfo.self, from: remote) ?? IMBaseRemoteInfo()
        info.displayString = message?.text

        // Set default cellType according to Message type.
        switch message?.messageType {
        case .MESSAGE_TYPE_TEXT:
            if msg.isSelf {
                info.cellType = .text
            } else {
                info.cellType = .aimsg
            }
        case .MESSAGE_TYPE_TIP:
            info.cellType = .tips
        case .MESSAGE_TYPE_CUSTOM:
            // Parse 自定义消息的cellType，和Attachment
            dealCustom(info: info, attachment: message?.attachment)
        default:
            info.cellType = .unknown
        }

        return info
    }

    private static func dealCustom(info: IMBaseRemoteInfo, attachment: V2NIMMessageAttachment?) {
        guard let attach = attachment else {
            return
        }
        info.cellType = .text
        let attachmentString = attach.raw

        // dlog("☁️🔥 V2NIMMessageAttachment's raw:\(attach.raw)")
        
        guard attachmentString.count > 0, let model = CodableHelper.decode(IMCustomAttachment.self, from: attachmentString) else {
            return
        }

        info.customAttachment = model
        guard let type = model.type else {
            dlog("☁️❌ wrong type, attach.raw is: \(attachmentString)")
            return
        }

        switch type {
        case .IMAGE:
            info.cellType = .image
            info.displayString = "[Image]"
        case .IM_SEND_GIFT:
            info.cellType = .gift
            info.displayString = "[Gift]"
        case .CALL:
            info.cellType = .phonecall
            info.displayString = model.getDisplayString()
        default:
            break
        }
    }

    // MARK: - Helper

    // MARK: Call

    
}
