//
//  UIButton+CCExtension.swift
//  SwiftProject
//
//  Created by Zhang, Joyce on 2024/3/2.
//

import Foundation
import UIKit

enum MSFBtnEdgeInsetsStyle {
    case Top                //image在上，label在下
    case Left               //image在左， label在右
    case Bottom             //image在下，label在上
    case Right              //image在右， label在左
}

extension UIButton {
    //更新btn的图文位置
   func updateBtnEdgeInsets(style: MSFBtnEdgeInsetsStyle, space: CGFloat) {
        let imageWidth = self.imageView?.frame.width ?? 0
        let imageHeight = self.imageView?.frame.height ?? 0
        
        let labelWidth = min(self.titleLabel?.intrinsicContentSize.width ?? 0, self.frame.width - imageWidth)
        let labelHeight = self.titleLabel?.intrinsicContentSize.height ?? 0
        
        var imageInsets = UIEdgeInsets.zero
        var labelInsets = UIEdgeInsets.zero
        
        switch style {
        case .Top:
            imageInsets = UIEdgeInsets.init(top: -(labelHeight + space) / 2, left: labelWidth / 2, bottom: (labelHeight + space) / 2, right: -labelWidth / 2 )
            labelInsets = UIEdgeInsets.init(top: (imageHeight + space) / 2, left: -imageWidth / 2, bottom: -(imageHeight + space) / 2, right: imageWidth / 2)
            break
        case .Left:
            imageInsets = UIEdgeInsets(top: 0, left: -space, bottom: 0, right: space)
            labelInsets = UIEdgeInsets(top: 0, left: space, bottom: 0, right: -space)
            break
        case .Bottom:
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: -(labelHeight + space / 2), right: -labelWidth)
            labelInsets = UIEdgeInsets(top: -(imageHeight + space / 2), left: -imageWidth, bottom: 0, right: 0)
            break
        case .Right:
            imageInsets = UIEdgeInsets(top: 0, left: labelWidth + space, bottom: 0, right: -(labelWidth + space))
            labelInsets = UIEdgeInsets(top: 0, left: -(imageWidth + space), bottom: 0, right: imageWidth + space)
            break
        }
        
        self.imageEdgeInsets = imageInsets
        self.titleEdgeInsets = labelInsets
        
    }
}
