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

@objcMembers class RecentReactionHistoryDefaultService : NSObject {
    
    private let sizeLimit = 8
    private let accountDataType = "io.element.recent_emoji"
    private let arrayKey = "recent_emoji"
    
    func sortedReactions(fromDictionary: [AnyHashable : Any]?) -> [RecentReaction] {
        guard let dictionary = fromDictionary else {
            return []
        }
        
        guard let array = dictionary[arrayKey] as? Array<Any> else {
            return []
        }
        
        var recentReactions = Array<RecentReaction>()
        
        for object in array {
            if let element = object as? [Any] {
                if let emoji = element[0] as? String, let count = element[1] as? Int {
                    recentReactions.append(RecentReaction(reaction: emoji, count: count))
                }
            }
        }
  
        return recentReactions.sorted()
    }
    
    func dictionary(fromReactions: [RecentReaction]) -> [AnyHashable : Any] {
        var array = Array<Any>()
        
        for reaction in fromReactions {
            array.append([reaction.reaction, reaction.count])
        }
        
        var dictionary = Dictionary<AnyHashable, Any>()
        dictionary[arrayKey] = array
        
        return dictionary
    }
}

extension RecentReactionHistoryDefaultService : RecentReactionHistoryService {
    
    func addReaction(reaction: String) {
        
        guard let session = LegacyAppDelegate.the().mxSessions.first as? MXSession else {
            return
        }
        
        var currentReaction = RecentReaction(reaction: reaction, count: 1)
        var recentReactions = self.sortedReactions(fromDictionary: session.accountData.accountData(forEventType: accountDataType))
        
        if let index = recentReactions.firstIndex(of: currentReaction) {
            currentReaction.count = recentReactions[index].count + 1
            recentReactions[index] = currentReaction
        } else {
            recentReactions.append(currentReaction)
        }
                
        let reactionDict = self.dictionary(fromReactions: recentReactions)
        
        session.setAccountData(reactionDict, forType: accountDataType, success: nil, failure: nil)
    }

    func reactions(defaultReactions: [String]) -> [String] {

        guard let session = LegacyAppDelegate.the().mxSessions.first as? MXSession else {
            return defaultReactions
        }
        
        let recentReactions = self.sortedReactions(fromDictionary: session.accountData.accountData(forEventType: "io.element.recent_emoji"))
        var currentReactions = Array<String>()
        
        for reaction in recentReactions {
            currentReactions.append(reaction.reaction)
        }
        for reaction in defaultReactions {
            if currentReactions.firstIndex(of: reaction) == nil {
                currentReactions.append(reaction)
            }
        }
        if currentReactions.count >= sizeLimit {
            return Array(currentReactions[..<sizeLimit])
        } else {
            return currentReactions
        }
        
    }
}
