//
/*
 * 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 class BWIAccountNotificationService:NSObject {
    
    struct AccountNotifications: Codable {
        
        enum CodingKeys: String, CodingKey {
            case analyticsPromt = "should_show_analytics_consent_dialog"
            case birthdayPromt = "should_show_ios_birthday_notification"
        }
        
        let analyticsPromt: Bool
        let birthdayPromt: Bool
        
        init(_ dict: [String: Any]) {

            if let analyticsVal = dict[AccountNotifications.CodingKeys.analyticsPromt.rawValue] as? Bool {
                analyticsPromt = analyticsVal
            } else {
                analyticsPromt = false
            }
            if let birthdayVal = dict[AccountNotifications.CodingKeys.birthdayPromt.rawValue] as? Bool {
                birthdayPromt = birthdayVal
            } else {
                birthdayPromt = false
            }
        }
    }
    
    private enum AccountDataTypes {
        static let notifications = "de.bwi.notifications"
    }
    
    let session: MXSession
    private lazy var serializationService: SerializationServiceType = SerializationService()
    
    init(mxSession: MXSession) {
        self.session = mxSession
    }
    
    func isNotificationShown(_ notificationKey: String) -> Bool {
        guard let notificationsDict = session.accountData.accountData(forEventType: AccountDataTypes.notifications) as? [String: Any] else {
            return false
        }
        
        let notifications = AccountNotifications(notificationsDict)
        return notifications.analyticsPromt
    }
    
    func setNotification(_ notificationKey: String, shown: Bool) {
        var notificationsDict = session.accountData.accountData(forEventType: AccountDataTypes.notifications) ?? [:]
        notificationsDict[AccountNotifications.CodingKeys.analyticsPromt.rawValue] = shown
        
        session.setAccountData(notificationsDict, forType: AccountDataTypes.notifications, success: nil, failure: nil)
    }
}
