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

import Foundation

enum MatomoGenerator {

    static var service: String {
        [
            Self.header,
            Self.setup,
            Self.logScreen,
            Self.logEvent,
            Self.footer
        ]
            .joined(separator: "\n")
    }

    // MARK: - Private vars

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

        class MatomoAnalyticsManager: AnalyticsManagerProtocol {

            // MARK: - Properties

            private var tracker: MatomoTracker

        """
    }

    private static var setup: String {
        """
            // MARK: - Init

            init(siteId: String, url: String) {
                debugPrint("[Matomo service] Server URL: \\(url)")
                debugPrint("[Matomo service] Site ID: \\(siteId)")
                tracker = MatomoTracker(
                    siteId: siteId,
                    baseURL: URL(string: url)!
                )

                #if DEBUG
                    tracker.dispatchInterval = 5
                #endif

                #if DEBUG
                    tracker.logger = DefaultLogger(minLevel: .verbose)
                #endif

                debugPrint("[Matomo service] Configured with content base: \\(tracker.contentBase?.absoluteString ?? "-")")
                debugPrint("[Matomo service] Opt out: \\(tracker.isOptedOut)")
            }

            // MARK: - Methods

        """
    }

    private static var logScreen: String {
        """
            func logScreen(name: String, path: String) {
                guard !tracker.isOptedOut else { return }
                guard let trackerUrl = tracker.contentBase?.absoluteString else { return }

                let urlString = URL(string: "\\(trackerUrl)" + "/" + "\\(path)" + "iOS")
                tracker.track(
                    view: [name],
                    url: urlString
                )
            }

        """
    }

    private static var logEvent: String {
        """
            func logEvent(
                name: String,
                action: String,
                category: String,
                params: [String: Any]?
            ) {
                guard !tracker.isOptedOut else { return }

                tracker.track(
                    eventWithCategory: category,
                    action: action,
                    name: name,
                    number: nil,
                    url: nil
                )
            }
        """
    }

    private static var footer: String {
        """
        }

        """
    }
}
