//
//  YHInterestTopicLayout.swift
//  galaxy
//
//  Created by edy on 2024/6/21.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHInterestTopicLayout: UICollectionViewFlowLayout {
     
    var dataSource: [String] = []
    weak var layoutDelegate: UICollectionViewDelegateFlowLayout?
    var collectionViewWidth = KScreenWidth-20.0*2
    override func prepare() {
        super.prepare()
        self.minimumInteritemSpacing = 8.0
        self.minimumLineSpacing = 8.0
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let attributes = super.layoutAttributesForElements(in: rect) else { return nil }
        
        var leftMargin = sectionInset.left
        var maxY: CGFloat = -1.0
        
        attributes.forEach { layoutAttribute in
            if layoutAttribute.frame.origin.y >= maxY {
                leftMargin = sectionInset.left
            }
            
            layoutAttribute.frame.origin.x = leftMargin
            leftMargin += layoutAttribute.frame.width + minimumInteritemSpacing
            maxY = max(layoutAttribute.frame.maxY, maxY)
        }
        
        return attributes
    }
    
    override var collectionViewContentSize: CGSize {
        get {
            let height = self.calculateHeight()
            return CGSize(width: self.collectionViewWidth, height: height)
        }
    }
    
    func calculateHeight() -> CGFloat {
        if self.dataSource.count <= 0 {
            return 0.0
        }
    
       guard let delegate = self.layoutDelegate else {
            return 0.0
        }
        let itemHeight = 24.0
        var currentX = 0.0
        var height = itemHeight
        
        for (index, _) in self.dataSource.enumerated() {
            if delegate.responds(to: #selector(UICollectionViewDelegateFlowLayout.collectionView(_:layout:sizeForItemAt:))) {
               let size = delegate.collectionView!(self.collectionView!, layout: self, sizeForItemAt: IndexPath(item: index, section: 0))
                if index == 0 {
                    currentX = size.width
                    height = itemHeight
                } else {
                    let targetX = currentX + self.minimumInteritemSpacing + size.width
                    if targetX <= self.collectionViewWidth {
                        currentX = targetX
                    } else {
                        currentX = size.width
                        height += self.minimumLineSpacing + itemHeight
                    }
                }
                printLog("calcaulte: \(height)")
            }
        }
        return height
    }
}
