//
/*
 * Copyright (c) 2023 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

final class LeaveRoomHelper {
    
    static func canLeaveRoom(_ session: MXSession, _ room: MXRoom) -> Bool {
        let myUserId = session.myUserId
        
        // None Admins can always leave the room
        if !self.isAdmin(session.myUserId, room) {
            return true
        }
        
        var canLeave = false
        var hasInvites = false
        
        // bwi #7561 add differenciation for admin and owner
        let myPowerLevel = self.powerLevel(session.myUserId, room)
        
        // admins can only leave if there is at least one other admin or owner
        // owners can only leave if there is another owner
        room.state { (state) in
            if let members = state?.members.joinedMembers {
                for user in members where user.userId != myUserId {
                    if self.powerLevel(user.userId, room) >= myPowerLevel
                    {
                        canLeave = true
                        break
                    }
                }
            }
            if state?.membersCount.invited ?? 0 > 0 {
                hasInvites = true
            }
        }
        // A single admin can leave the room if he is the only member and there are no pending invites. User can leave DMs without a rule.
        if !canLeave && self.isOnlyMember(room) && !hasInvites || room.isDirect {
            canLeave = true
        }
        
        return canLeave
    }
    
    static private func powerLevel(_ userId: String, _ room: MXRoom) -> Int {
        var powerLevel: Int = 0
        
        room.state { (state) in
            powerLevel = state?.powerLevelOfUser(withUserID: userId) ?? 0
        }
        
        return powerLevel
    }
    
    static private func isAdmin(_ userId: String, _ room: MXRoom) -> Bool {
        var admin = false
        
        room.state { (state) in
            let powerLevels = state?.powerLevels
            let userPowerLevel = state?.powerLevelOfUser(withUserID: userId)
            let roomPowerLevel = RoomPowerLevelHelper.roomPowerLevel(from: userPowerLevel ?? RoomPowerLevel.user.rawValue)
            
            if roomPowerLevel == RoomPowerLevel.admin || roomPowerLevel == RoomPowerLevel.owner {
                admin = true
            }
        }
        
        return admin
    }
    
    static func isOnlyMember(_ room: MXRoom) -> Bool {
        var memberCount = 0
        
        room.state { (state) in
            if let members = state?.members.joinedMembers {
                memberCount = members.count
            }
        }
        return (memberCount == 1)
    }
}
