import { Injectable, PLATFORM_ID } from '@angular/core';
import { AppInsights } from 'applicationinsights-js';
import { environment } from '@environment';
import { isPlatformBrowser } from '@angular/common';

@Injectable()
export class AppInsightService {
    public logPageView(name?: string, url?: string, properties?: any, measurements?: any, duration?: number) {
        AppInsights.trackPageView(name, url, properties, measurements, duration);
    }

    public logEvent(name: string, properties?: any, measurements?: any) {
        AppInsights.trackEvent(name, properties, measurements);
    }

    public logException(exception: Error, handledAt?: string, properties?: any, measurements?: any) {
        AppInsights.trackException(exception, handledAt, properties, measurements);
    }

    public logTrace(message: string, properties?: any, severityLevel?: any) {
        AppInsights.trackTrace(message, properties, severityLevel);
    }

    public configure() {
        if (!AppInsights.config) {
            AppInsights.downloadAndSetup(environment.appInsights);
            AppInsights.queue.push(() => {
                AppInsights.context.addTelemetryInitializer((envelope) => {
                    if (!envelope.data.baseData.properties) {
                        envelope.data.baseData.properties = {};
                    }
                    envelope.data.baseData.properties.Env = environment.appInsights.env;
                    envelope.data.baseData.properties.Application = environment.appInsights.application;
                    envelope.data.baseData.properties.Category = environment.appInsights.category;
                });
            });
        }
    }
}

@Injectable()
export class NullAppInsightService implements AppInsightService {
    public logPageView() {
        // do nothing
    }

    public logEvent() {
        // do nothing
    }

    public logException() {
        // do nothing
    }

    public logTrace() {
        // do nothing
    }

    public configure() {
        // do nothing
    }
}

export const appInsightsProvider = {
    provide: AppInsightService,
    useFactory: (platformId) => new NullAppInsightService(), // to be replaced with null service for SSR
    deps: [PLATFORM_ID],
};
