import Foundation
import TigaseSwift

// FIXME: solve linter suppressed issues
//swiftlint: disable force_unwrapping
class PresenceRosterEventHandler: XmppServiceEventHandler {
    let events: [Event] = [RosterModule.ItemUpdatedEvent.TYPE, PresenceModule.BeforePresenceSendEvent.TYPE, PresenceModule.SubscribeRequestEvent.TYPE]

    func handle(event: Event) {
        switch event {
        case let e as RosterModule.ItemUpdatedEvent:
            NotificationCenter.default.post(name: DBRosterStore.ITEM_UPDATED, object: e)

        case let e as PresenceModule.BeforePresenceSendEvent:
            if XmppService.instance.applicationState == .active {
                e.presence.show = Presence.Show.online
                e.presence.priority = 5
            } else {
                e.presence.show = Presence.Show.away
                e.presence.priority = 0
            }
            if let manualShow = Settings.statusType.getString() {
                e.presence.show = Presence.Show(rawValue: manualShow)
            }
            e.presence.status = Settings.statusMessage.getString()

        case let e as PresenceModule.SubscribeRequestEvent:
            guard let from = e.presence.from else {
                return
            }
            var info: [String: AnyObject] = [:]
            info["account"] = e.sessionObject.userBareJid!
            info["sender"] = from.bareJid
            DispatchQueue.main.async {
                NotificationCenter.default.post(name: XmppService.PRESENCE_AUTHORIZATION_REQUEST, object: self, userInfo: info)
            }

        default:
            break
        }
    }
}
