//
/*
 * 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
import MatrixSDK

class UserLabelDefaultService : NSObject {
    var currentRoom: MXRoom? = nil
    var completion: ((Bool) -> Void)? = nil
}

extension UserLabelDefaultService : UserLabelService {
    @objc func setCompletion(_ completion:@escaping((Bool) -> Void)) {
        self.completion = completion
    }
    
    @objc func setRoom(_ room: MXRoom) {
        self.currentRoom = room
    }
    
    @objc func setUserLabel(userLabel: String?, user: String) {
        guard let room = self.currentRoom, let completion = self.completion else {
            return
        }
        
        let savedLabel = self.getUserLabel(user: user)
        
        if savedLabel == userLabel {
            completion(false)
            return
        }
        
        room.state { (state) in
            guard let state = state else {
                completion(false)
                return
            }
            
            if state.powerLevels.events[BWIBuildSettings.shared.bwiUserLabelEventTypeString] == nil {
                if var newContent = state.powerLevels.jsonDictionary() as? [String : Any] {
                    if var events = newContent["events"] as? [String : Any] {
                        
                        events[BWIBuildSettings.shared.bwiUserLabelEventTypeString] = RoomPowerLevel.admin.rawValue
                        newContent["events"] = events
                   
                        room.sendStateEvent(.roomPowerLevels, content: newContent, stateKey: "", completion: { response in
                            if response.isFailure {
                                completion(false)
                                return
                            }
                        })
                    }
                    
                }
            }
            
            if var currentLabel = state.stateEvents(with: .custom(BWIBuildSettings.shared.bwiUserLabelEventTypeString))?.last?.content {
                if userLabel != nil {
                    currentLabel[user] = userLabel
                } else {
                    currentLabel.removeValue(forKey: user)
                }
                
                room.sendStateEvent(.custom(BWIBuildSettings.shared.bwiUserLabelEventTypeString), content: currentLabel, stateKey: "", completion: { response in
                    completion(response.isSuccess)
                })
            } else if userLabel != nil {
                var newUserLabel = Dictionary<String, Any>()
                newUserLabel[user] = userLabel
                room.sendStateEvent(.custom(BWIBuildSettings.shared.bwiUserLabelEventTypeString), content: newUserLabel, stateKey: "", completion: { response in
                    completion(response.isSuccess)
                })
            }
        }
    }
    
    @objc func getUserLabel(user: String) -> String? {
        guard let room = self.currentRoom else {
            return nil
        }
        
        var label: String? = nil
        
        room.state { (state) in
            guard let state = state else {
                return
            }
            
            if let labels = state.stateEvents(with: .custom(BWIBuildSettings.shared.bwiUserLabelEventTypeString))?.last?.content {
                if let tmp = labels[user] as? String {
                    label = tmp
                }
            }
        }
        
        return label
    }
}
