//
//  LNIMChatImageMessageCell.swift
//  Lanu
//
//  Created by OneeChan on 2025/12/5.
//

import Foundation
import UIKit
import SnapKit


private extension LNIMMessageData {
    var thumbImageUrl: String? {
        imMessage.imageElem?.imageList.first { $0.type == .IMAGE_TYPE_THUMB }?.url
    }
    
    var originImageUrl: String? {
        imMessage.imageElem?.imageList.first { $0.type == .IMAGE_TYPE_ORIGIN }?.url
    }
    
    var largeImageUrl: String? {
        imMessage.imageElem?.imageList.first { $0.type == .IMAGE_TYPE_LARGE }?.url
    }
}


class LNIMChatImageMessageCell: LNIMChatBaseMessageCell {
    private let imageIc = UIImageView()
    private let contentLabel = UILabel()
    
    private var curItem: LNIMMessageData?
    
    override func setupViews() {
        super.setupViews()
        
        imageIc.contentMode = .scaleAspectFill
        imageIc.layer.cornerRadius = 12
        imageIc.clipsToBounds = true
        container.addSubview(imageIc)
        imageIc.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalTo(266)
            make.height.equalTo(202)
        }
        
        imageIc.onTap { [weak self] in
            guard let self else { return }
            guard let curItem else { return }
            if curItem.imMessage.isSelf, let url = curItem.content {
                presentImagePreview([url], 0)
            } else if let url = curItem.largeImageUrl {
                presentImagePreview([url], 0)
            }
        }
    }
    
    override func update(_ data: LNIMMessageData, viewModel: LNIMChatViewModel) {
        super.update(data, viewModel: viewModel)
        
        curItem = data
        
        let thumbUrl = data.content ?? ""
        if thumbUrl.hasPrefix("http") {
            imageIc.sd_setImage(with: URL(string: thumbUrl))
        } else {
            imageIc.sd_setImage(with: URL(fileURLWithPath: thumbUrl))
        }
    }
}
