import UIKit
import TigaseSwift

// FIXME: solve linter suppressed issues
// swiftlint: disable force_unwrapping
// swiftlint: disable force_cast
class MainTabBarController: CustomTabBarController, UITabBarControllerDelegate {
    public static let RECENTS_TAB = 0
    public static let ROSTER_TAB = 1
    public static let MORE_TAB = 2

    override func viewDidLoad() {
        super.viewDidLoad()

        self.delegate = self

        NotificationCenter.default.addObserver(self, selector: #selector(updateMoreBadge), name: XmppService.ACCOUNT_STATE_CHANGED, object: nil)
    }

    @objc func updateMoreBadge(notification: Notification) {
        let xmppService = (notification.object as! XmppService)
        let cnt = xmppService.getClients(filter: { (client) -> Bool in
                return client.state != .connected
            })
            .count + AccountManager.getAccounts().filter({ (name) -> Bool in
                return AccountSettings.lastError(BareJID(name)).getString() != nil
            })
            .count
        DispatchQueue.main.async {
            self.tabBar.items![MainTabBarController.MORE_TAB].badgeValue = cnt == 0 ? nil : cnt.description
            if cnt == 0 {
                (UIApplication.shared.delegate as? AppDelegate)?.updateApplicationIconBadgeNumber(completionHandler: nil)
            }
        }
    }

    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        guard viewController.restorationIdentifier == "SettingsNavigationControllerDummy" else {
            return true
        }
        DispatchQueue.main.async {
            let controller = UIStoryboard(name: "Settings", bundle: nil).instantiateViewController(withIdentifier: "SettingsNavigationController")
            self.present(controller, animated: true, completion: nil)
        }
        return false
    }
}
