import UIKit
import Eureka

final class ImageGridCell: Cell<[String]>, CellType {
    private var grid: ImageGrid!

    required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        self.grid = ImageGrid(columns: 3, spacing: 2)
        self.grid.translatesAutoresizingMaskIntoConstraints = false
        self.contentView.addSubview(self.grid)
        NSLayoutConstraint.activate([
            self.grid.leadingAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.leadingAnchor),
            self.grid.trailingAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.trailingAnchor),
            self.grid.topAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.topAnchor),
            self.grid.bottomAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.bottomAnchor)
        ])
        self.height = { UITableView.automaticDimension }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority,
                                          verticalFittingPriority: UILayoutPriority) -> CGSize {
        self.grid.preferredMaxLayoutWidth = self.bounds.size.width - self.layoutMargins.left - self.layoutMargins.right
        return super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)
    }

    override func setup() {
        super.setup()
        
        self.grid.selectionChanged = { index in
            if let row = self.row as? ImageGridRow {
                row.select(at: index)
            }
        }
    }

    override func update() {
        super.update()
        self.textLabel?.text = nil
        self.detailTextLabel?.text = nil
        self.grid.set(images: row.value ?? [])
    }
}

final class ImageGridRow: Row<ImageGridCell>, RowType {
    private var selectionCallback: ((Int) -> Void)?
    
    required init(tag: String?) {
        super.init(tag: tag)
        cellProvider = CellProvider<ImageGridCell>()
    }
    
    fileprivate func select(at index: Int) {
        self.selectionCallback?(index)
    }
    
    @discardableResult
    func onDidSelected(_ callback: @escaping (Int) -> Void) -> ImageGridRow {
        self.selectionCallback = callback
        return self
    }
}
