//
/*
 * Copyright (c) 2022 BWI GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import Foundation

@objc enum CollapsedACLEvents : Int {
    case none = 0
    case mixed = 1
    case all = 2
}

@objc class FederationEventHelper: NSObject {
    @objc static let shared = FederationEventHelper()
    
    @objc func statusInTimelineForEvent( event: MXEvent, roomState: MXRoomState ) -> String {
        if let allowedServerList = event.wireContent["allow"] as? [String] {
            if allowedServerList.count > 1 || allowedServerList.first == "*" {
                return BWIL10n.eventFormatterAclAllowFederation
            } else {
                if event.prevContent != nil && !isFirstACLEvent(event: event, roomState: roomState) {
                    return BWIL10n.eventFormatterAclDisallowFederation
                } else {
                    return BWIL10n.eventFormatterAclDisallowAtStart
                }
            }
        } else {
            return BWIL10n.eventFormatterAclDisallowFederation
        }
    }
    
    func isFirstACLEvent( event: MXEvent, roomState: MXRoomState ) -> Bool {
        if let events = roomState.stateEvents(with: .roomServerACL) {
            if let firstEvent = events.first {
                if firstEvent.eventId == event.eventId {
                    return true
                } else {
                    return false
                }
            }
        }
        
        return true
            
    }
    
    @objc func isCollapsedACLEvents( events: [MXEvent]) -> CollapsedACLEvents {
        var aclEventCount = 0, otherEventCount = 0
        for event in events {
            if event.eventType != .roomServerACL {
                otherEventCount += 1
            } else {
                aclEventCount += 1
            }
        }
        
        if aclEventCount > 0 && otherEventCount == 0 {
            return .all
        } else if otherEventCount > 0 && aclEventCount == 0 {
            return .none
        } else {
            return .mixed
        }
    }
}
