//
//  UIViewController+AddChild.swift
//  react-native-firework-sdk
//
//  Created by Jeff Zheng on 2021/12/30.
//

import Foundation

/// util method for managing child viewcontroller
extension UIViewController {
    /// add viewController view to the receiver's viewController.view,
    /// and set the constraints align view.safeAreaLayoutGuide
    /// - Parameter viewController: ViewController to be added
    public func attachChild(_ viewController: UIViewController) {
        let constraints = viewController.view.constraints(equalTo: view.safeAreaLayoutGuide)
        attachChild(
            viewController,
            to: view,
            using: constraints)
    }

    /// add viewController view to the receiver's viewController.view, and set the constraints on the four sides
    /// - Parameters:
    ///   - viewController: UIViewController to be added
    ///   - container: the container view to add child view
    public func attachChild(
        _ viewController: UIViewController,
        to containerView: UIView
    ) {
        let constraints = viewController.view.constraints(equalTo: containerView)
        attachChild(
            viewController,
            to: containerView,
            using: constraints)
    }

    /// add viewController view to the receiver's viewController.view, and set the constraints on the four sides
    /// - Parameters:
    ///   - viewController: UIViewController to be added
    ///   - container: the container view to add child view
    ///   - constraints: constraints between container and viewController.view
    public func attachChild(
        _ viewController: UIViewController,
        to container: UIView,
        using constraints: [NSLayoutConstraint]
    ) {
        guard viewController.parent == nil else { return }
        addChild(viewController)
        container.addSubview(viewController.view)
        viewController.view.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate(
            constraints
        )
        viewController.didMove(toParent: self)
    }

    /// remove from parent controller
    public func detachFromParent() {
        guard self.parent != nil else {
            return
        }

        self.willMove(toParent: nil)
        self.removeFromParent()
        self.view.removeFromSuperview()
    }
}
