//
//  CustomTextMessageSizeCalculator.swift
//  ChatExample
//
//  Created by Vignesh J on 30/04/21.
//  Copyright © 2021 MessageKit. All rights reserved.
//

import MessageKit
import UIKit

class TSTextLayoutSizeCalculator: TSLayoutSizeCalculator {
    
    
    //MARK: ###################################消息label###################################
    //消息容器的 UIEdgeInsets
    static var cellMessagelabelEdge:UIEdgeInsets = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)
    static var messageLabelFont = UIFont.font(size: 16.0)
    static var cellMessagelabelMinSize:CGSize = CGSizeMake(24, 24)
    
    
    var cellMessagelabelLeadingMaxWidth:CGFloat{
        messageContainerLeadingMaxWidth - Self.cellMessagelabelEdge.left - Self.cellMessagelabelEdge.right
    }
    
    var cellMessagelabelTraingMaxWidth:CGFloat{
        messageContainerTraingMaxWidth - Self.cellMessagelabelEdge.left - Self.cellMessagelabelEdge.right
    }
    
    //消息容器的高度
    override func cellContentHeight(for message: MessageType,at indexPath: IndexPath, fromCurrentSender: Bool)-> CGFloat {
        let superH = super.cellContentHeight(for: message, at: indexPath, fromCurrentSender: fromCurrentSender)
        let size = messageLabelSize(for: message, at: indexPath, fromCurrentSender: fromCurrentSender)
        var height = size.height + Self.cellMessagelabelEdge.top + Self.cellMessagelabelEdge.bottom

        if height < superH {
            height = superH
        }

        return height
    }
    
    func messageLabelSize(for message: MessageType,at _: IndexPath, fromCurrentSender: Bool) -> CGSize{
        let attributedText: NSAttributedString
//        var sendText = ""
        let textMessageKind = message.kind
        switch textMessageKind {
        case .attributedText(let text):
            attributedText = text
//            sendText = text.string
        case .text(let text), .emoji(let text):
            attributedText = NSAttributedString(string: text, attributes: [.font: Self.messageLabelFont])
//            sendText = text
        default:
            fatalError("messageLabelSize received unhandled MessageDataType: \(message.kind)")
        }
        let maxWidth = fromCurrentSender ? cellMessagelabelTraingMaxWidth: cellMessagelabelLeadingMaxWidth
//        let textSize = sendText.height(ofFont: Self.messageLabelFont, maxWidth: maxWidth)
        var size = attributedText.size(consideringWidth: maxWidth)
        size.width = size.width + 10
        let minSize = Self.cellMessagelabelMinSize
        if size.width < minSize.width {
            size.width = minSize.width
        }
        if size.height < minSize.height {
            size.height = minSize.height
        }
        
        return size
    }
    
}
