//
//  ConfirmLoadMoreCollectionViewCell.swift
//  Tusker
//
//  Created by Shadowfacts on 9/21/22.
//  Copyright © 2022 Shadowfacts. All rights reserved.
//

import UIKit
import Combine

class ConfirmLoadMoreCollectionViewCell: UICollectionViewCell {
    
    var confirmLoadMore: PassthroughSubject<Void, Never>?
    var isLoading: Bool {
        get {
            button.configuration?.showsActivityIndicator ?? false
        }
        set {
            var config = button.configuration!
            config.showsActivityIndicator = newValue
            button.configuration = config
        }
    }
    
    private var button: UIButton!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = .appGroupedBackground
        
        let label = UILabel()
        label.text = "Infinite scrolling is off. Do you want to keep going?"
        label.font = .preferredFont(forTextStyle: .body)
        label.adjustsFontForContentSizeCategory = true
        label.textColor = .secondaryLabel
        label.textAlignment = .natural
        label.numberOfLines = 0
        
        var config = UIButton.Configuration.tinted()
        config.title = "Load More"
        config.imagePadding = 4
        button = UIButton(configuration: config, primaryAction: UIAction(handler: { [unowned self] _ in
            self.confirmLoadMore?.send()
        }))
        
        let stack = UIStackView(arrangedSubviews: [
            label,
            button,
        ])
        stack.axis = .vertical
        stack.distribution = .fill
        stack.spacing = 4
        stack.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(stack)
        NSLayoutConstraint.activate([
            stack.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
            stack.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
            stack.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8),
            stack.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8),
        ])
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
