import UIKit

class CloseableViewController: UIViewController {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        configureNavigationItem()
    }

    func configureNavigationItem() {
        guard let viewControllers = self.navigationController?.viewControllers else {
            self.createCloseButton()
            return
        }

        if viewControllers.count == 1 {
            self.createCloseButton()
        }

        self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .done, target: nil, action: nil)
    }

    func createCloseButton() {
        if self.navigationItem.leftBarButtonItem == nil {
            let closeButtonItem = UIBarButtonItem(
                title: closeButtonTitle(),
                style: UIBarButtonItem.Style.plain,
                target: self,
                action: #selector(closeButtonWasTapped(_:))
            )
            self.navigationItem.leftBarButtonItem = closeButtonItem
        }
    }

    func closeButtonTitle() -> String {
        return "Close"
    }

    @objc func closeButtonWasTapped(_ sender: UIBarButtonItem? = nil) {
        if let viewControllers = self.navigationController?.viewControllers , viewControllers.count > 1 {
            _ = self.navigationController?.popViewController(animated: true)
        } else {
            self.dismiss(animated: true, completion: nil)
        }
    }
}
