VPNAnalytics.swift 1.46 KB
//
//  VPNAnalytics.swift
//  VPNAnalytics
//
//  Created by Mihail Konoplitskyi on 01.09.2022.
//

import Foundation

public final class VPNAnalytics: NSObject {
    private static let analyitcsAPIService = AnalyticsAPIService()
    
    private static var isUserInstallEventAlreadyLogged: Bool {
        get {
            return UserDefaults.standard.bool(forKey: VPNAnalyticsConstants.VPNAnalyticsEvent.install.rawValue)
        }
        
        set (newValue) {
            UserDefaults.standard.set(newValue, forKey: VPNAnalyticsConstants.VPNAnalyticsEvent.install.rawValue)
        }
    }
    
    public static func configure(applicationToken: String, baseUrl: String) {
        analyitcsAPIService.applicationToken = applicationToken
        AnalyticsAPIService.baseUrl = baseUrl
        checkAndSendInstallEventIfNeeded()
    }
    
    private static func checkAndSendInstallEventIfNeeded() {
        guard isUserInstallEventAlreadyLogged else {
            // could not find install event in user defaults
            // sending this event to server
            logEvent(eventType: .install)
            return
        }
    }
    
    public static func logEvent(
        eventType: VPNAnalyticsConstants.VPNAnalyticsEvent,
        params: [String: String]? = nil) {
        analyitcsAPIService.logEvent(eventType: eventType, eventParams: params) {
            if eventType == .install {
                isUserInstallEventAlreadyLogged = true
            }
        }
    }
}