//
//  LTScrollContainer.swift
//  LegendTeam
//
//  Created by dong on 2022/5/5.
//

import Combine
import UIKit

/// Default: leading,trailing is 0,  stack's alignment is leading
class LTScrollContainer: UIView {
    public var scrollView: UIScrollView!
    var container: UIView!
    public var stack: UIStackView!

//    var listViewDidScrollCallback: ((UIScrollView) -> Void)?
    private var cancellables = Set<AnyCancellable>()
    
    var stackEdge:UIEdgeInsets?{
        didSet{
            stack.snp.updateConstraints { make in
                make.edges.equalToSuperview().inset(stackEdge ?? .zero)
            }
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = .clear

        scrollView = UIScrollView()
        scrollView.contentInsetAdjustmentBehavior = .never
        addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
//            make.top.equalToSuperview().offset(UIWindow.navBarTotalHeight)
//            make.bottom.equalToSuperview().offset(-64 - UIWindow.safeAreaBottom)
            make.top.bottom.equalToSuperview()
        }

        container = UIView()
        scrollView.addSubview(container)
        container.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalToSuperview()
        }

        stack = UIStackView()
        stack.axis = .vertical
        stack.alignment = .leading
        container.addSubview(stack)
        stack.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 0, bottom: 16, right: 0))
        }

        scrollContainerEvent()
    }

    private func scrollContainerEvent() {
//        scrollView.publisher(for: \.contentOffset)
//            .sink {[weak self] offset in
//                //print("Scroll offset is now \(offset)")
//                if let scroll = self?.scrollView {
//                    self?.listViewDidScrollCallback?(scroll)
//                }
//            }
//            .store(in: &cancellables)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
