//
//  FirebaseGenerator.swift
//
//
//  Created by Loris Perret on 05/12/2023.
//

import Foundation

enum FirebaseGenerator {

    static var service: String {
        [
            FirebaseGenerator.header,
            FirebaseGenerator.logScreen,
            FirebaseGenerator.logEvent,
            FirebaseGenerator.footer
        ]
            .joined(separator: "\n")
    }
    
    // MARK: - Private vars

    private static var header: String {
        """
        // MARK: - Firebase

        class FirebaseAnalyticsManager: AnalyticsManagerProtocol {
        """
    }
    
    private static var logScreen: String {
        """
            func logScreen(name: String, path: String) {
                var parameters = [
                    AnalyticsParameterScreenName: name as NSObject
                ]
        
                Analytics.logEvent(
                    AnalyticsEventScreenView,
                    parameters: parameters
                )
            }
        
        """
    }
    
    private static var logEvent: String {
        """
            func logEvent(
                name: String,
                action: String,
                category: String,
                params: [String: Any]?
            ) {
                var parameters: [String:NSObject] = [
                    "action": action as NSObject,
                    "category": category as NSObject,
                ]
                
                if let supplementaryParameters = params {
                    for (newKey, newValue) in supplementaryParameters {
                        if parameters.contains(where: { (key: String, value: NSObject) in
                            key == newKey
                        }) {
                            continue
                        }
                        
                        parameters[newKey] = newValue as? NSObject
                    }
                }
                
                Analytics.logEvent(
                    name.replacingOccurrences(of: [" "], with: "_"),
                    parameters: parameters
                )
            }
        """
    }
    
    private static var footer: String {
        """
        }
        
        """
    }
}
